[英]PHP TCP socket server hangs when accepting a new connection
I'm trying to set up a TCP socket server, which should support many client connections at the same time, together with receiving and sending data. 我正在尝试设置一个TCP套接字服务器,该服务器应同时支持许多客户端连接以及接收和发送数据。
For this purpose I'm trying to use PHP's socket_select();
为此,我正在尝试使用PHP的
socket_select();
due to server always hanged on socket_read();
由于服务器始终挂在
socket_read();
process, where it should continue, no matter if there were data, or not. 过程中,无论是否存在数据,都应在哪里继续。 I Tried to run following code below, but it always hangs on a new client connection.
我试图在下面的代码中运行,但是它始终挂在新的客户端连接上。
// TCP socket created
$clients = array($socket);
while (true) { // Infinite loop for server
$newsock = socket_accept($socket);
if ($newsock !== false) {
// Adds a new client
$clients[] = $newsock;
}
$read = $clients;
$write = NULL;
$except = NULL;
$num_changed_sockets = socket_select($read, $write, $except, 0);
if ($num_changed_sockets === false) {
// Error here
} else if ($num_changed_sockets > 0) {
// Something happened
if (in_array($socket, $read)) {
$key = array_search($socket, $read);
unset($read($key]);
}
foreach ($read as $read_socket) {
$data = socket_read($read_socket, 128); // This should not hang!
if ($data === false) {
// Disconnect client
}
// Reads data, sends answer...
}
}
// Something to send for all clients
}
Is it also possible to use socket_select();
是否也可以使用
socket_select();
without having a copy of my clients in an array, where the listener is included? 没有在数组中包含我的客户的副本,其中包含侦听器? Just having a clean array for clients.
只是为客户准备了一个干净的阵列。
默认情况下,套接字是阻塞的 ,您也应该将被动侦听套接字(在您的情况下$socket
)放入传递给socket_select
的读取集中,当您可以接受新连接时,它将可读。
Just set the listening socket $socket
to non-blocking mode. 只需将监听套接字
$socket
设置为非阻塞模式即可。 Clients get connected and data is being read, but the client disconnects are not handled in real time (there is a pretty big delay on it). 客户端已建立连接并且正在读取数据,但是客户端断开连接无法实时处理(延迟很大)。 Is there reason for that?
有什么理由吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.