我正在尝试在端口 8195 上创建一个简单的监听器。当我在 PHP CLI 条件下尝试以下代码块时,它仅显示“测试”一次,然后挂起。如果我删除文件“votifier.run”(该文件设计为开/关开关),它仍然会继续挂起。它从不显示“客户端已连接”。
此外,如果我在脚本运行时尝试通过端口 8195 上的 Telnet 连接到主机,我只会收到一条连接失败消息。就好像它在寻找一种联系并且不放弃。
// Set the IP and port to listen to
$address = 'localhost';
$port = 8195;
// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
// Bind the socket to an address/port
socket_bind($sock, $address, $port);
// Start listening for connections
socket_listen($sock);
// Loop continuously
while ( file_exists('votifier.run') ) {
echo 'Test';
$client = socket_accept($sock);
if( $client ) {
echo 'Client connected';
// Don't hang on slow connections
socket_set_timeout($client, 5);
// Send them our version
socket_write("VOTIFIER MCWEBLINK\n");
// Read the 256 byte block
$block = socket_read($client, 256);
...
答案: socket_accept() 通常会挂起,直到建立连接。如果尝试进行连接,脚本将继续,但由于套接字是在本地主机上创建的,因此它只接受来自本地主机的连接。
修复方法是使用您的外部 IP,而不是“localhost”或“127.0.0.1”。然后您可以 Telnet 到它。
最佳答案
我只是在这里猜测,但是您尝试绑定(bind)的地址是否不应该是主机名?
If the socket is of the AF_INET family, the address is an IP in dotted-quad notation (e.g. 127.0.0.1).
编辑
好的,我已经获取了您的脚本并尝试重现您的错误,但未能成功。它存在一些缺陷,但不会导致 telnet 客户端的连接尝试失败。
由于上述情况均不适用,让我们逐一检查 list :
- 套接字模块已加载/编译
- localhost 确实解析为 127.0.0.1
- 该端口未被任何其他正在运行的应用程序占用
- 没有任何类型的防火墙规则会阻止 telnet 客户端与服务器之间的通信
- 允许您连接的计算机连接到服务器主机(如果不允许,请尝试同一主机)
- 在 while 循环中检查的文件确实存在
- 您确定脚本中没有其他 fatal error 会阻止您发布的代码段运行
这些是我能想到的所有可能的错误源,atm。首先尝试修复小缺陷,然后检查 list 。
if( $client ) {
echo 'Client connected';
// Don't hang on slow connections
socket_set_option(
$client,
SOL_SOCKET,
SO_RCVTIMEO | SO_SNDTIMEO,
array('sec' => 5, 'usec' => 0)
);
// Send them our version
socket_write($client, "VOTIFIER MCWEBLINK\n");
^^^^^^^
// Read the 256 byte block
$block = socket_read($client, 256);
关于php - socket_accept 似乎卡在第一个连接上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11948268/