/framework/experimental/pherver/ChatServer.php

http://zoop.googlecode.com/ · PHP · 49 lines · 32 code · 6 blank · 11 comment · 6 complexity · afed47910da72a2c050bc8702315b917 MD5 · raw file

  1. <?php
  2. class ChatServer extends Pherver
  3. {
  4. protected function handleNew($newsock)
  5. {
  6. // send the client a welcome message
  7. socket_write($newsock, "no noobs, but ill make an exception :)\n".
  8. "There are ".(count($this->clients) - 1)." client(s) connected to the server\n");
  9. socket_getpeername($newsock, $ip);
  10. echo "New client connected: {$ip}\n";
  11. }
  12. protected function handleRead($read_sock)
  13. {
  14. // read until newline or 1024 bytes
  15. // socket_read while show errors when the client is disconnected, so silence the error messages
  16. $data = @socket_read($read_sock, 1024, PHP_NORMAL_READ);
  17. // check if the client is disconnected
  18. if ($data === false)
  19. {
  20. // remove client for $this->clients array
  21. $key = array_search($read_sock, $this->clients);
  22. unset($this->clients[$key]);
  23. echo "client disconnected.\n";
  24. // continue to the next client to read from, if any
  25. continue;
  26. }
  27. // trim off the trailing/beginning white spaces
  28. $data = trim($data);
  29. // check if there is any data after trimming off the spaces
  30. if (!empty($data))
  31. {
  32. // send this to all the clients in the $this->clients array (except the first one, which is a listening socket)
  33. foreach ($this->clients as $send_sock)
  34. {
  35. // if its the listening sock or the client that we got the message from, go to the next one in the list
  36. if ($send_sock == $this->sock || $send_sock == $read_sock)
  37. continue;
  38. // write the message to the client -- add a newline character to the end of the message
  39. socket_write($send_sock, $data."\n");
  40. }
  41. }
  42. }
  43. }