PHP中使用tcp或者udp请求数据,分为两种
1:需要向udp发送数据才能获取到返回值的
/** *$service_port 端口号 *$address 服务器地址 *$in 发送的参数 **/ public function Send_socket_xdcoder_udp($service_port, $address, $in) { // 采用php socket技术使用UDP协议连接设备 $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); @socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array( "sec" => 2, "usec" => 0 )); // 发送命令 @socket_sendto($socket, $in, strlen($in), 0, $address, $service_port); @socket_recvfrom($socket, $buffer, 1024, 0, $address, $service_port); // 关闭连接 socket_close($socket); if (! empty($buffer)) { return $buffer; } else { echo "fail"; } }
2:udp直接就是吐数据不需要发请求
#设置超时不起作用不知道什么情况
/** *$service_port 端口号 *$address 服务器地址 **/ public function getUdp($service_port, $address) { //服务器信息 //如果是tcp 直接写tcp $server = "udp://$address:$service_port"; //消息结束符号 $msg_eof = "\n"; $socket = stream_socket_server($server, $errno, $errstr, STREAM_SERVER_BIND); if (!$socket) { die("$errstr ($errno)"); } $inMsg = stream_socket_recvfrom($socket, 1024, 0, $peer); fclose($socket); return $inMsg; }
socket请求设置请求超时
/** * Created by PhpStorm. * function: Get_socket_xdcoder_udp * Description: 获取udp数据 * User: Xiaoxie * @param $service_port * @param $address * @return mixed * */ public function Get_socket_xdcoder_udp($service_port, $address) { $socket = socket_create(AF_INET,SOCK_DGRAM,SOL_UDP); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array( "sec" => 1, "usec" => 0 )); $ok = @socket_bind($socket,$address,$service_port); if ( $ok === false ) { echo "socket_bind() failed:reason:" . socket_strerror( socket_last_error( $socket ) ); } $from = ''; $cport = 0; @socket_recvfrom($socket, $buffer, 1024,0, $from, $cport); // echo $from; return $buffer; }