PHP警告:socket_recv()无限等待



我写了下面的代码来连接java网络套接字服务器。客户端可以成功连接到服务器。(我希望如此)。我的问题是,当我删除socket_recv的行时,它不会等待并抛出任何错误。但是php在这个行/块上无限等待。

PHP版本为5.5.12

<?php
error_reporting(E_ALL);
$service_port = 2002;
$address = 'x.x.x.x';
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "n";
} else {
    echo "OK.n";
}
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "n";
} else {
    echo "OK.n";
}
$input = "(({"u":"994774100040","ut":0,"lon":28.838424,"lox":28.941421,"lax":41.074951,"lan":40.965122,"rg":0.0,"pr":0.0,"di":0.0,"e":false,"p":0,"r":0,"l":1,"cr":0,"ac":2,"st":0,"t":10,"a":5,"ls":1}))";
$out = '';
socket_write($socket, $input, strlen($input));
echo "OK.n";
$buf = '';
//infinite waiting on below line
if (false !== ($bytes = socket_recv($socket, $buf, 1024,0))) {
    echo "Read $bytes bytes from socket_recv(). Closing socket...";
} else {
    echo "socket_recv() failed; reason: " .
    socket_strerror(socket_last_error($socket)) . "n";
}
socket_close($socket);
echo $buf . "n";
echo "OK.nn";
?>

我解决了添加以下握手代码的问题

$key = com_create_guid();
$header = "GET  HTTP/1.1rn";
$header.= "Upgrade: WebSocketrn";
$header.= "Connection: Upgradern";
$header.= "Host: x.x.x.x:2002rn";
$header.= "Origin: http://localhost:81rn";
$header.= "Sec-WebSocket-Key: " . $key . "rn";
$header.= "rn";
socket_write($socket, $header, strlen($header));

Web套接字服务器等待来自客户端的标头进行握手。

相关内容

  • 没有找到相关文章

最新更新