public function testNumberOfWritesToStream() { $stream = $this->getMock('React\\Stream\\WritableStreamInterface'); $called = 0; $stream->expects($this->any())->method('write')->will($this->returnCallback(function () use(&$called) { ++$called; })); $channel = new BufferedChannel(); // initially nothing written $channel->connect($stream); $this->assertEquals(0, $called); // writing does send $channel->writeMessage('first'); $this->assertEquals(1, $called); // writing does send again $channel->writeMessage('second'); $this->assertEquals(2, $called); // writing after disconnect does not send $channel->disconnect($stream); $channel->writeMessage('third'); $this->assertEquals(2, $called); // connecting does not send $channel->connect($stream); $this->assertEquals(2, $called); // connecting with offset will send remaining message $channel->disconnect($stream); $channel->connect($stream, 2); $this->assertEquals(3, $called); }
protected function handleSse(Request $request, Response $response) { $headers = $request->getHeaders(); $id = isset($headers['Last-Event-ID']) ? $headers['Last-Event-ID'] : null; $response->writeHead(200, array('Content-Type' => 'text/event-stream')); $this->channel->connect($response, $id); $response->on('close', function () use($response) { $this->channel->disconnect($response); }); }
$channel = new BufferedChannel(); $http = new React\Http\Server($socket); $http->on('request', function (Request $request, Response $response) use($channel) { if ($request->getPath() === '/') { $response->writeHead('200', array('Content-Type' => 'text/html')); $response->end(file_get_contents(__DIR__ . '/../01-simple-periodic/eventsource.html')); return; } echo 'connected' . PHP_EOL; $headers = $request->getHeaders(); $id = isset($headers['Last-Event-ID']) ? $headers['Last-Event-ID'] : null; $response->writeHead(200, array('Content-Type' => 'text/event-stream')); $channel->connect($response, $id); $response->on('close', function () use($response, $channel) { echo 'disconnected' . PHP_EOL; $channel->disconnect($response); }); }); $port = isset($argv[2]) ? $argv[2] : 8000; $connector = new TcpConnector($loop); $connector->create('127.0.0.1', $port)->then(function (Stream $stream) use($channel) { $buffer = ''; $stream->on('data', function ($data) use(&$buffer, $channel) { $buffer .= $data; while (($pos = strpos($buffer, "\n")) !== false) { $channel->writeMessage(substr($buffer, 0, $pos)); $buffer = substr($buffer, $pos + 1); } }); }, 'printf'); $socket->listen(isset($argv[1]) ? $argv[1] : 0, '0.0.0.0');