php实现一个简单的socket

PHP技术
340
0
0
2022-04-20
//确保在连接客户端时不会超时
set_time_limit(0);
//设置IP和端口号
$address = "127.0.0.1";
$port = 54321;
$socketServer = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() fail:" . socket_strerror(socket_last_error()) . "/n");
//设置为阻塞模式
socket_set_block($socketServer) or die("socket_set_block() fail:" . socket_strerror(socket_last_error()) . "/n");
//绑定端口
$result = socket_bind($socketServer, $address, $port) or die("socket_bind() fail:" . socket_strerror(socket_last_error()) . "/n");
//开始监听
$result = socket_listen($socketServer, 4) or die("socket_listen() fail:" . socket_strerror(socket_last_error()) . "/n");

do {//接收连接请求并返回一个子Socket来处理客户端和服务器间的信息   
    $sock = socket_accept($socketServer) or  die("socket_accept() failed: reason: " . socket_strerror(socket_last_error()) . "/n");while($sock){//读取客户端数据   
        echo "Read client data \n";

        $length = socket_read($sock, 4);
        $length = unpack('i', $length);
        echo "length:$length[1]   \n";

        $request = socket_read($sock, $length[1]);
        echo "$request:$request   \n";

        //数据传送 向客户端写入返回结果   
        $msg = "this is response message \n";
        $msgLength = strlen($msg);
        $msgLength = pack('i', $msgLength);socket_write($sock, $msgLength);socket_write($sock, $msg, strlen($msg)) or die("socket_write() failed: reason: " . socket_strerror(socket_last_error()) ."/n");break;}

} while (true);
socket_close($socketServer);