Advertisement
Tomasz_svk

UDP server in PHP

Jan 16th, 2013
804
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.39 KB | None | 0 0
  1. <?php
  2. $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
  3. if(!socket_bind($sock,0,$argv[1])){
  4.     printMessage("Couldn't bind socket");
  5.     exit;
  6. }
  7. socket_set_nonblock($sock);
  8.  
  9. $clients = array();
  10.  
  11. $clients = array($sock);
  12.  
  13. $c = array();
  14.    
  15. $wait=1;
  16.  
  17. $users = array();
  18.  
  19. while (true) {
  20.     usleep($wait);
  21.     // create a copy, so $clients doesn't get modified by socket_select()
  22.     $read = array($sock);
  23.     $write = array();
  24.     $except = NULL;
  25.     $buf="";
  26.    
  27.     // get a list of all the clients that have data to be read from
  28.     // if there are no clients with data, go to next iteration
  29.     if (socket_select($read, $write, $except, 0) < 1){
  30.         $wait = 100;
  31.         continue;
  32.      }
  33.      $wait = 1;
  34.     $from = '';
  35.     $port = 0;
  36.     socket_recvfrom($sock, $buf, 1024, 0, $from, $port);
  37.     echo "Received $buf from remote address $from and remote port $port and got: " .$buf. PHP_EOL;
  38.  
  39.     $data = explode("|",trim($buf));
  40.     switch($data[0]){
  41.         case 1:
  42.             $users[count($users)] = array('ip' => $from, 'port'=>$port, 'name'=>$data[1]);
  43.             break;
  44.         case 2:
  45.             for($i=0;$i<count($users);$i++){
  46.                 if($users[$i]['name']==$data[1]){
  47.                     $buf = $users[$i]['ip']."|".$users[$i]['port'];
  48.                     echo "Sending ".$buf.PHP_EOL;
  49.                     socket_sendto($sock, $buf, strlen($buf), 0, $from, $port);
  50.                     break;
  51.                 }
  52.             }
  53.            
  54.             break;
  55.     }
  56.  
  57. }
  58.  
  59. // close the listening socket
  60. socket_close($sock);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement