Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
- if(!socket_bind($sock,0,$argv[1])){
- printMessage("Couldn't bind socket");
- exit;
- }
- socket_set_nonblock($sock);
- $clients = array();
- $clients = array($sock);
- $c = array();
- $wait=1;
- $users = array();
- while (true) {
- usleep($wait);
- // create a copy, so $clients doesn't get modified by socket_select()
- $read = array($sock);
- $write = array();
- $except = NULL;
- $buf="";
- // get a list of all the clients that have data to be read from
- // if there are no clients with data, go to next iteration
- if (socket_select($read, $write, $except, 0) < 1){
- $wait = 100;
- continue;
- }
- $wait = 1;
- $from = '';
- $port = 0;
- socket_recvfrom($sock, $buf, 1024, 0, $from, $port);
- echo "Received $buf from remote address $from and remote port $port and got: " .$buf. PHP_EOL;
- $data = explode("|",trim($buf));
- switch($data[0]){
- case 1:
- $users[count($users)] = array('ip' => $from, 'port'=>$port, 'name'=>$data[1]);
- break;
- case 2:
- for($i=0;$i<count($users);$i++){
- if($users[$i]['name']==$data[1]){
- $buf = $users[$i]['ip']."|".$users[$i]['port'];
- echo "Sending ".$buf.PHP_EOL;
- socket_sendto($sock, $buf, strlen($buf), 0, $from, $port);
- break;
- }
- }
- break;
- }
- }
- // close the listening socket
- socket_close($sock);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement