PHP发送UDP消息支持绑定端口

更新于 2022-06-19 19:59 377
专栏: PHP 标签: php socket

  1. function SendUdpMsg($service_port, $address, $msg){
  2. // 采用php socket技术使用UDP协议连接设备
  3. $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
  4. @socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array(
  5. "sec" => 2,
  6. "usec" => 0
  7. ));
  8. // 绑定IP/PORT
  9. socket_bind($socket, '192.168.1.105', 8000);
  10. // 发送命令
  11. socket_sendto($socket, $msg, strlen($msg), 0, $address, $service_port);
  12. // if (($ret = socket_listen($socket, 5)) < 0) {
  13. // echo "socket_listen() failed: reason: " . socket_strerror($ret) . "\n";
  14. // exit;
  15. // }
  16. if (false !== ($bytes = socket_recv($socket, $buf, 1024, MSG_PEEK))) {
  17. echo "Read $bytes bytes from socket_recv(). Closing socket...";
  18. } else {
  19. echo "socket_recv() failed; reason: " . socket_strerror(socket_last_error($socket)) . "\n";
  20. }
  21. // 关闭连接
  22. socket_close($socket);
  23. return $buf;
  24. }