@walkor 大大 一个socket_select() 通信问题

var

这是php官网sokcet_select()下的一个例子,我运行发现一个问题,就是多个客户端telnet 方式连接时,如果一个客户端输入消息但是没有按回车发送出去,那么其他的telnet客户端的消息发出去都不会广播到其他telnet。
@walkor 如何加判断解决这一问题呢 求科普

<?php
$port = 8888;

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);

socket_bind($sock, 0, $port);

socket_listen($sock);

$clients = array($sock);

$addr = '';
$prot = '';
while (true) {

    $read = $clients;

    if (socket_select($read, $write = NULL, $except = NULL, null) < 1) {

        continue;
    }

    if (in_array($sock, $read)) {

        $clients[] = $newsock = socket_accept($sock);

        socket_getpeername($newsock, $addr, $port);

        socket_write($newsock, "welcome clients:" . $addr . " port:" . $port . "\n" . "thre are " . (count($clients) - 1) . ' clients connected to the server' . "\n");

        echo "New client connected: {$addr}\n";

        $key = array_search($sock, $read);
        unset($read);
    }

    foreach ($read as $read_sock) {

        $data = @socket_read($read_sock, 1024, PHP_NORMAL_READ);

        if ($data === false || $data == '') {

            $key = array_search($read_sock, $clients);
            unset($clients);
            echo "client disconnected.\n";

            continue;
        }

        $data = trim($data);

        if (!empty($data)) {

            foreach ($clients as $send_sock) {

                if ($send_sock == $sock || $send_sock == $read_sock)
                    continue;

                socket_write($send_sock, $data . "\n");

            }

        }

    }
}

socket_close($sock);
3176 1 0
1个回答

walkor 打赏

一步一步打日志看下

  • 暂无评论
年代过于久远,无法发表回答
×
🔝