Advertisement
iiddaannyy

sockets

Aug 21st, 2012
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.61 KB | None | 0 0
  1. <?php
  2. function echoClients(array $clients) {
  3.     if (count($clients) == 0) {
  4.         echo "No clients connected.\n";
  5.         return;
  6.     }
  7.     $names = array();
  8.     foreach ($clients as $client) {
  9.         if (!is_null($client['name']))
  10.             $names[] = $client['name'];
  11.     }
  12.     echo "Clients connected: ".implode(', ', $names).".\n";
  13. }
  14. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  15. socket_bind($socket, '127.0.0.1', 100);
  16. socket_listen($socket);
  17. $clients = array();
  18. while (true) {
  19.     $read = array($socket);
  20.     foreach ($clients as $client) {
  21.         $read[] = $client['socket'];
  22.     }
  23.     $ready = socket_select($read, $write = null, $except = null, null);
  24.     if (in_array($socket, $read, true)) {
  25.         $clients[] = array(
  26.             'socket' => socket_accept($socket),
  27.             'name' => null
  28.         );
  29.         socket_write($clients[count($clients)-1]['socket'], "Welcome to ChatServer!\nWrite your name: ");
  30.         $ready--;
  31.     }
  32.     if ($ready == 0) continue;
  33.     $num_clients = count($clients);
  34.     for ($i = 0; $i < $num_clients; $i++) {
  35.         if (in_array($clients[$i]['socket'], $read, true)) {
  36.             $input = socket_read($clients[$i]['socket'], 256);
  37.             if (empty($input)) {
  38.                 socket_close($clients[$i]['socket']);
  39.                 echo "--{$clients[$i]['name']} has left. ";
  40.                 unset($clients[$i]);
  41.                 echoClients($clients);
  42.             }
  43.             else {
  44.                 if (is_null($clients[$i]['name'])) {
  45.                     $clients[$i]['name'] = trim(preg_replace('/\s/', ' ', $input));
  46.                     echo "--{$clients[$i]['name']} has joined. ";
  47.                     echoClients($clients);
  48.                 }
  49.                 else {
  50.                     echo "{$clients[$i]['name']} says: $input";
  51.                 }
  52.             }
  53.         }
  54.     }
  55.     $clients = array_merge(array(), $clients);
  56. }
  57. socket_close($socket);
  58. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement