欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

解析:通过php socket并借助telnet实现简单的聊天程序

程序员文章站 2022-03-20 08:59:07
以下是通过php的socket扩展模块实现的一个简单的消息处理服务器端:绑定在一个本机的端口,监听客户端的连接,接收数据并转发给发送者之外的所有客户端socket_serv...

以下是通过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