Heim > Artikel > Backend-Entwicklung > 解析:通过php socket并借助telnet实现简单的聊天程序_PHP教程
以下是通过php的socket扩展模块实现的一个简单的消息处理服务器端:绑定在一个本机的端口,监听客户端的连接,接收数据并转发给发送者之外的所有客户端
socket_server.php
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);
通过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