博瑞博客

现在位置:首页 > PHP > 使用PHP进行UDP Socket编程

使用PHP进行UDP Socket编程

江湖    PHP    2016-2-26    1237    0评论

本文主要是通过简单的例子介绍下UDP Socket编程.


1.UDP服务器

  1. <?php
  2. //Reduce errors
  3. error_reporting(~E_WARNING);
  4.  
  5. //Create a UDP socket
  6. if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) {
  7. $errorcode = socket_last_error();
  8. $errormsg = socket_strerror($errorcode);
  9. die("Couldn't create socket: [$errorcode] $errormsg \n");
  10. }
  11.  
  12. echo "Socket created \n";
  13.  
  14. // Bind the source address
  15. if( !socket_bind($sock, "0.0.0.0" , 11300) ) {
  16. $errorcode = socket_last_error();
  17. $errormsg = socket_strerror($errorcode);
  18. die("Could not bind socket : [$errorcode] $errormsg \n");
  19. }
  20.  
  21. echo "Socket bind OK \n";
  22.  
  23. //Do some communication, this loop can handle multiple clients
  24. while(1) {
  25. echo "Waiting for data ... \n";
  26.  
  27. //Receive some data
  28. $r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
  29. echo "$remote_ip : $remote_port -- " . $buf;
  30.  
  31. //Send back the data to the client
  32. socket_sendto($sock, "OK " . $buf , 100 , 0 , $remote_ip , $remote_port);
  33. }
  34.  
  35. socket_close($sock);

在Terminal运行:

$php socket_udp_server.php


Socket created

Socket bind OK

Waiting for data …


2.UDP客户端

  1. <?php
  2. //Reduce errors
  3. error_reporting(~E_WARNING);
  4.  
  5. $server = '127.0.0.1';
  6. $port = 11300;
  7.  
  8. if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) {
  9. $errorcode = socket_last_error();
  10. $errormsg = socket_strerror($errorcode);
  11. die("Couldn't create socket: [$errorcode] $errormsg \n");
  12. }
  13.  
  14. echo "Socket created \n";
  15.  
  16. //Communication loop
  17.  
  18. while(1) {
  19.  
  20. //Take some input to send
  21.  
  22. echo 'Enter a message to send : ';
  23. $input = fgets(STDIN);
  24.  
  25. //Send the message to the server
  26. if( ! socket_sendto($sock, $input , strlen($input) , 0 , $server , $port)) {
  27.  
  28. $errorcode = socket_last_error();
  29.  
  30. $errormsg = socket_strerror($errorcode);
  31.  
  32. die("Could not send data: [$errorcode] $errormsg \n");
  33.  
  34. }
  35.  
  36. //Now receive reply from server and print it
  37.  
  38. if(socket_recv ( $sock , $reply , 2045 , MSG_WAITALL ) === FALSE) {
  39.  
  40. $errorcode = socket_last_error();
  41.  
  42. $errormsg = socket_strerror($errorcode);
  43.  
  44. die("Could not receive data: [$errorcode] $errormsg \n");
  45.  
  46. }
  47.  
  48. echo "Reply : $reply";
  49. }

在Terminal运行客户端程序:

$php socket_udp_client.php

Socket created

Enter a message to send : udp testonly

Reply : OK udp testonly

Enter a message to send :

 

 

 

 

评论一下分享本文赞助博瑞

赞助博瑞X

扫码赞助博瑞
联系站长
博瑞博客
挤眼亲亲咆哮开心想想可怜糗大了委屈哈哈小声点右哼哼左哼哼疑问坏笑赚钱啦悲伤耍酷勾引厉害握手耶嘻嘻害羞鼓掌馋嘴抓狂抱抱围观威武给力
提交评论

清空信息
关闭评论