我有一个PHP套接字服务器,需要与多个客户端进行通信。我知道if(socket_listen($sock, 5)
监听5个客户。但是,当我尝试连接第二个设备时却没有连接,就像第一个设备的连接阻止了其他连接一样。
当服务器和客户端进行通信并且由于某种原因连接已关闭时,我也遇到问题,然后如果我尝试再次连接同一设备,否则将无法正常工作。然后,我需要重新启动服务器,以便它能够再次接受连接。
<?php
require "init.php";
$sql = "SELECT * FROM `info` where sent = 0 order by id desc";
error_reporting(E_ALL);
/* Allow the script to hang around waiting for connections. */
set_time_limit(0);
/* Turn on implicit output flushing so we see what we're getting
* as it comes in. */
ob_implicit_flush();
$address = '192.168.50.30';
$port = 3005;
if(($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
if(socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
if(socket_listen($sock, 5) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
do {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
/* Send Welcome. */
$msg = "HELLO".chr(0);
socket_write($msgsock, utf8_encode ($msg), strlen($msg));
do {
$result = $con->query($sql);
$row = $result->fetch_assoc();
if(!empty($row["Token"])){
$msg = $row["Token"]. chr(0);
socket_write($msgsock, utf8_encode($msg), strlen($msg));
$result = $con->query("update info set sent = 1 where id = ".$row["id"]);
}
// $talkback = $_SERVER['REMOTE_ADDR']." Said: '$buf'.\n".chr(0);
// socket_write($msgsock, $talkback, strlen($talkback));
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
?>