Advertisement
Serafim

Untitled

Jan 29th, 2014
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.59 KB | None | 0 0
  1. <?php
  2. namespace Rocket
  3. {
  4.     use Rocket\Socket\Stream;
  5.  
  6.     class Server
  7.     {
  8.         private $_stream;
  9.         private $_host = '127.0.0.1';
  10.         private $_port = '8080';
  11.  
  12.         public function __construct($host = null, $port = null)
  13.         {
  14.             if ($host) { $this->_host = $host; }
  15.             if ($port) { $this->_port = $port; }
  16.  
  17.             $this->_stream = new Stream($this->_host, $this->_port);
  18.         }
  19.  
  20.         public function stream($cb = null)
  21.         {
  22.             if ($cb) {
  23.                 $this->_stream->connection()->send($cb);
  24.             }
  25.             return $this->_stream;
  26.         }
  27.  
  28.         public function close()
  29.         {
  30.             fclose($this->_stream);
  31.         }
  32.     }
  33. }
  34.  
  35. namespace Rocket\Socket
  36. {
  37.     class Stream
  38.     {
  39.         private $_socket;
  40.  
  41.         public function __construct($host, $port)
  42.         {
  43.             $this->_socket = stream_socket_server("tcp://${host}:${port}", $errno, $errstr);
  44.         }
  45.  
  46.         public function connection()
  47.         {
  48.             while (true) {
  49.                 $stream = stream_socket_accept($this->_socket, -1);
  50.                 $cb = yield;
  51.                 $cb($stream);
  52.             }
  53.         }
  54.     }
  55. }
  56.  
  57.  
  58. namespace
  59. {
  60.     // Запускаеам:
  61.     $server = new Rocket\Server('0.0.0.0', '8080');
  62.     while (true) {
  63.         $server->stream(function($connection){
  64.             fwrite($connection, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\nHello world!");
  65.             fclose($connection);
  66.         });
  67.     }
  68.     $server->stream()->close();
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement