PHPUDP协议时超时设置

mac2025-05-25  33

stream_set_timeout — Establecer un perido de tiempo de espera en un flujo

意思就是在建立流的过程中设置超时,看下面代码:

/** * @param string $sendMsg 发送指定内容 * @param string $ip ip地址 * @param string $port 端口 * @return bool|string 返回读取内容 */ public function sndAgreement($sendMsg = '', $ip = '192.168.1.118', $port = '9100'){ // 创建UDP链接 $handle = stream_socket_client("udp://{$ip}:{$port}", $errno, $errstr,5); // 不存在则异常 if( !$handle ){ die("ERROR: {$errno} - {$errstr}\n"); } // 设置读取超过4s为超时 stream_set_timeout($handle, 4); // 向句柄中发送数据 fwrite($handle, $sendMsg."\n"); // 读取内容,设置大小为1024字节 $result = fread($handle, 1024); // 关闭句柄 fclose($handle); // 返回读取的内容 return $result; }

 

最新回复(0)