/framework/experimental/pherver/Pherver.php

http://zoop.googlecode.com/ · PHP · 85 lines · 49 code · 20 blank · 16 comment · 4 complexity · de983f4db656a31ff8de10fdeaf49a99 MD5 · raw file

  1. <?php
  2. // this originated from an example on the php website http://us2.php.net/socket_select
  3. abstract class Pherver
  4. {
  5. protected $clients, $sock;
  6. function listen($host, $port)
  7. {
  8. $port = 9050;
  9. // create a streaming socket, of type TCP/IP
  10. $this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  11. // set the option to reuse the port
  12. socket_set_option($this->sock, SOL_SOCKET, SO_REUSEADDR, 1);
  13. // "bind" the socket to the address to "localhost", on port $port
  14. // so this means that all connections on this port are now our resposibility to send/recv data, disconnect, etc..
  15. socket_bind($this->sock, $host, $port);
  16. // start listen for connections
  17. socket_listen($this->sock);
  18. return $this->sock;
  19. }
  20. function run($host, $port)
  21. {
  22. // listen on localhost:9050
  23. $this->sock = Pherver::listen($host, $port);
  24. // create a list of all the clients that will be connected to us..
  25. // add the listening socket to this list
  26. $this->clients = array($this->sock);
  27. while (true)
  28. {
  29. echo "starting the loop\n";
  30. // create a copy, so $this->clients doesn't get modified by socket_select()
  31. $read = $this->clients;
  32. // get a list of all the clients that have data to be read from
  33. // if there are no clients with data, go to next iteration
  34. echo "selecting a socket\n";
  35. $nchanged = socket_select($read, $write = NULL, $except = NULL, 10);
  36. if($nchanged === false)
  37. {
  38. echo "socket_select() failed, reason: " . socket_strerror(socket_last_error()) . "\n";
  39. continue;
  40. }
  41. if($nchanged < 1)
  42. continue;
  43. echo "printing readable sockets\n";
  44. print_r($read);
  45. // check if there is a client trying to connect
  46. if(in_array($this->sock, $read))
  47. {
  48. // accept the client, and add him to the $this->clients array
  49. $this->clients[] = $newsock = socket_accept($this->sock);
  50. $this->handleNew($newsock);
  51. // remove the listening socket from the clients-with-data array
  52. $key = array_search($this->sock, $read);
  53. unset($read[$key]);
  54. }
  55. // loop through all the clients that have data to read from
  56. foreach ($read as $read_sock)
  57. {
  58. $this->handleRead($read_sock);
  59. }
  60. }
  61. socket_close($this->sock);
  62. }
  63. abstract protected function handleNew($newsock);
  64. abstract protected function handleRead($read_sock);
  65. }