您可以轻松地扩展第一个示例以处理任意数量的连接,而不仅仅是一个连接。
#!/usr/bin/env php
<?php
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$address = '127.0.0.1';
$port = 10000;
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() 失败:原因: " . socket_strerror(socket_last_error()) . "\n";
}
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() 失败:原因: " . socket_strerror(socket_last_error($sock)) . "\n";
}
if (socket_listen($sock, 5) === false) {
echo "socket_listen() 失败:原因: " . socket_strerror(socket_last_error($sock)) . "\n";
}
$clients = array();
do {
$read = array();
$read[] = $sock;
$read = array_merge($read,$clients);
if(socket_select($read,$write = NULL, $except = NULL, $tv_sec = 5) < 1)
{
continue;
}
if (in_array($sock, $read)) {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() 失败:原因: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
$clients[] = $msgsock;
$key = array_keys($clients, $msgsock);
$msg = "\n欢迎来到 PHP 测试服务器。\n" .
"您是客户端编号: {$key[0]}\n" .
"要退出,请输入 'quit'。 要关闭服务器,请输入 'shutdown'。\n";
socket_write($msgsock, $msg, strlen($msg));
}
foreach ($clients as $key => $client) { if (in_array($client, $read)) {
if (false === ($buf = socket_read($client, 2048, PHP_NORMAL_READ))) {
echo "socket_read() 失败:原因: " . socket_strerror(socket_last_error($client)) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
if ($buf == 'quit') {
unset($clients[$key]);
socket_close($client);
break;
}
if ($buf == 'shutdown') {
socket_close($client);
break 2;
}
$talkback = "客户端 {$key}: 您说 ' "$buf'。\n";
socket_write($client, $talkback, strlen($talkback));
echo "$buf\n";
}
}
} while (true);
socket_close($sock);
?>