/** * Start listening for new connections * * @param string $address * @param array $context * @return this */ public function listen($address, array $context = array()) { $address = is_numeric($address) ? "tcp://0.0.0.0:{$address}" : $address; $context = stream_context_create($context); $this->stream = @stream_socket_server($address, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context); $server = $this; if (!is_resource($this->stream) || $errstr) { $this->emit('error', array($errstr, $this)); return $this; } $this->emit('listening', array($this)); $this->iloop->add($this->stream, IOLoop::READ, function ($master, $ioloop) use($server) { $client = stream_socket_accept($master, 0); $client = new IOStream($ioloop, $client, IOStream::DUPLEX); $client->reader = 'fgets'; $client->writer = 'stream_socket_sendto'; $client->on('close', function ($client) { stream_socket_shutdown($client->stream, STREAM_SHUT_RDWR); }); $server->emit('connection', array($client)); }); return $this; }