以下是通過php的socket擴展模塊實現的一個簡單的消息處理服務器端:綁定在一個本機的端口,監聽客戶端的連接,接收數據並轉發給發送者之外的所有客戶端
socket_server.php
復制代碼 代碼如下:
#!/usr/bin/env php
<?php
//author:zhxia
if(!extension_loaded('sockets')){
die('the sockets extension is not loaded!');
}
const PORT=9981;
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP) or die('socket create error!');
#通過設置這個選項,進行端口的重用
socket_set_option($socket,SOL_SOCKET,SO_REUSEADDR,1);
socket_bind($socket,0,PORT);
socket_listen($socket);
#使用非阻塞模式
socket_set_nonblock($socket);
echo 'listen on port '.PORT.'...'.PHP_EOL;
$clients=array($socket);
while(TRUE){
$read=$clients;
$write=$except=array();
//通過select系統調用,檢測socket的狀態是否改變
if(socket_select($read,$write,$except,0)<1){
continue;
}
//檢測是否有客戶端來進行連接
if(in_array($socket,$read)){
$clients[]=$newsocket=socket_accept($socket);
socket_write($newsocket,"welcome!\nthere are ".(count($clients)-1)." client here\n");
socket_getpeername($newsocket,$ip);
echo "new client connected:$ip\n";
$key=array_search($newsocket,$read);
unset($read[$key]);
}
foreach($read as $read_socket){
$data=@socket_read($read_socket,1024,PHP_NORMAL_READ);
if($data===false){
//如果沒有取到數據,說明該客戶端已經斷開
$key=array_search($read_socket,$clients);
unset($clients[$key]);
echo "client disconnectd.\n";
continue;
}
$data=trim($data);
if(!empty($data)){
foreach($clients as $write_socket){
//排除服務器端和自身,然後將數據發送給所有的其他客戶端
if($write_socket==$socket||$write_socket==$read_socket){
continue;
}
socket_write($write_socket,"$data\n");
}
}
}
}
socket_close($socket);
啟動服務端:
zhxia@zhxia-pc:~/sh/php$ ./socket_server.php
listen on port 9981...
通過telnet進行連接:
zhxia@haozudb:~$ telnet 192.168.187.16 9981
Trying 192.168.187.16...
Connected to 192.168.187.16.
Escape character is '^]'.
welcome!
there are 1 client here