我有一个创建套接字连接的函数,并侦听实验室机器通过TCP发送的HL7消息的端口号。
如果实验室机器没有发送任何东西,我的监听功能会继续听。有没有办法指定它应该只听10秒钟然后如果没有消息,应该抛出错误?
$address = '0.0.0.0';
$port = 5600;
// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
// Bind the socket to an address/port
$bind = socket_bind($sock, $address, $port);
// Start listening for connections
socket_listen($sock);
$client = socket_accept($sock);
// Read the input from the client
$input = socket_read($client, 2024);
// Strip all white spaces from input
$segs = explode("|",$input);
// Close the master sockets
$close = socket_close($sock);
答案 0 :(得分:0)
这是解决方案:
socket_set_option($sock,SOL_SOCKET,SO_RCVTIMEO,array("sec"=>10,"usec"=>0)); // after 10 seconds socket will destroy the connection. Also you can set and uses
答案 1 :(得分:0)
这看起来像the XY problem。
您想要衡量的东西充当客户端而不是暗示您可能想要做的不仅仅是在脚本中检测打开的TCP连接,例如捕获一些数据。此外,底层操作系统有许多复杂,经过良好测试,可靠且可调的机制,用于跟踪连接状态。
虽然您可以像stefo91建议并尝试操纵接收超时,但我不确定这是否适用于等待初始连接。更好的解决方案是set the socket to non-blocking。别忘了:
除非你希望你的脚本烧掉大量资源而无需做任何事情。
但是根据您没有告诉我们的大量信息,正确的解决方案可能是将一个脚本作为服务器运行,将第二个脚本作为监视器运行。第二种可能是轮询/解析netstat的输出以检查连接。