无法从套接字读取(挂起) [英] Can't read from socket (hangs)
问题描述
编辑:对不起,不小心张贴了另一个问题的标题。已修复。
Sorry, accidentally posted with a title for a different question. Fixed.
嘿,
我使用PHP连接到本地C ++套接字服务器状态在一个Web应用程序和几个守护程序之间。我可以发送数据到套接字服务器,但不能从它接收;它只是阻塞在 socket_read()
,并无限期挂起。我忘记了一些愚蠢的东西(比如NULL字符或换行符的不同组合)? PHP如下:
I'm using PHP to connect to a local C++ socket server to keep state between a web app and a couple of daemons. I can send data to the socket server, but not receive from it; it just blocks on socket_read()
and hangs indefinitely. Am I forgetting something dumb (like a NULL character or a different combination of newline characters)? The PHP is below:
socket_connect($sock, $addr, $port);
socket_write($sock, 'Hello world');
$str = '';
while($resp = socket_read($sock, 1000))
$str .= $resp;
socket_close($sock);
die("Server said: {$str}");
套接字服务器的相关部分如下(注意<
和>>
运算符重载):
The related part of the socket server is below (note that the <<
and >>
operators are overloaded):
std::string data;
sock >> data;
sock << data << std::endl;
其中>>
c $ c> Socket :: recv(std :: string&)和>>
调用 Socket :: send(const std :: string&)
。
Where >>
calls Socket::recv(std::string&)
and >>
calls Socket::send(const std::string&)
.
这种方法适用于(例如)telnet,但PHP不想播放不错。
This works fine from (for example) telnet, but PHP doesn't want to play nice. Any thoughts/suggestions are appreciated.
推荐答案
PHP中的套接字在大多数编程语言中都默认在阻塞模式下打开,除非使用 socket_set_nonblock
设置。
Sockets in PHP, as in most programming languages, are opened in blocking mode by default, unless set otherwise using socket_set_nonblock
.
这意味着除非发生超时/错误或接收到数据,否则<$
This means that unless a timeout/error occurs or data is received, socket_read
will hang there forever.
由于您的终止字符似乎是一个新行,请尝试:
Since your termination character seems to be a new line, try that:
while($resp = socket_read($sock, 1000)) {
$str .= $resp;
if (strpos($str, "\n") !== false) break;
}
socket_close($sock);
die("Server said: $str");
这篇关于无法从套接字读取(挂起)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!