php – 无法连接到非阻塞套接字
作者:互联网
这让我疯了.我必须在php 5.3中创建一个非常简单的非阻塞套接字脚本,其中客户端连接到服务器,都使用非阻塞套接字.
我已经尝试了phpsocketdaemon和php manual的示例,但在这两种情况下,当我尝试连接到服务器时,我收到以下错误:
socket_connect() [function.socket-connect]: unable to connect [10035]:
A non-blocking socket operation could not be completed immediately
发生错误的客户端脚本:
$service_port = 2002;
$address = '127.0.0.1';
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_nonblock($socket);
$result = socket_connect($socket, $address, $service_port);
...
我在Win 7上使用Zend Server 5.6.0 SP1的免费版本.
有谁知道如何解决这个问题或知道一个简单易懂的非阻塞套接字客户端/服务器脚本的例子?
解决方法:
当你设置套接字非阻塞时,你不能指望socket_connect()的结果如果连接则返回TRUE,否则返回FALSE.
If the socket is non-blocking then this function returns FALSE with an error Operation now in progress.
任何语言都是如此.您必须设置套接字“阻塞”,或者必须在检查文件描述符是否已正确连接之前轮询/选择.
在PHP中,您可以在一小段时间后调用socket_connect()函数来检查它是否返回true,false或等待超时到期.
试试这段代码[EDITED修复超时例程的小错误]:
<?php
$service_port = 2002;
$address = '127.0.0.1';
$timeout = 3;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_nonblock($socket);
$error = NULL;
$attempts = 0;
$timeout *= 1000; // adjust because we sleeping in 1 millisecond increments
$connected = FALSE;
while (!($connected = @socket_connect($socket, $address, $service_port)) && ($attempts++ < $timeout)) {
$error = socket_last_error();
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
echo "Error Connecting Socket: ".socket_strerror($error) . "\n";
socket_close($socket);
return NULL;
}
usleep(1000);
}
if (!$connected) {
echo "Error Connecting Socket: Connect Timed Out After " . $timeout/1000 . " seconds. ".socket_strerror(socket_last_error()) . "\n";
socket_close($socket);
return NULL;
}
?>
标签:php,sockets,php-socket 来源: https://codeday.me/bug/20190716/1481245.html