A primer for getting an async socket server up and running with ReactPHP, and Websocket server with Ratchet. The code that goes with: https://github.com/catch404/dallasphp-201308
// libevent, libev, or stream_select, gives you back // an object that implements the loop interface. $loop->run(); // run the loop. // ... except our app does nothing... so...
$loop->addPeriodicTimer(int $time, callable $func); // run every $time seconds. both return Timer objects with various methods, most useful of which may be the cancel() method. - see: src/React/EventLoop/Timer/Timer.php
connection events so that the // socket server knows what to do about them. $server->on( ‘connection’, function($cx) { echo “a client has connected.”, PHP_EOL; });
all your data. example: windows telnet sends every keypress as it happens. unix telnet waits until new line. messages could get broken up into multiple packets and arrive to the client in the wrong order. that is how the internet works. so as they arrive the NIC may choose to send you what it can construct properly *now* and wait until later to send the rest.
check the buffer each time to see if it has a complete message yet or not. super simple example: LF based protocols (fgets()) new line based protocol? does your data have a new line in it? start of buffer to the new line is a complete message.
public function onClose() { } public function onError() { } public function onMessage() { } } Ratchet\Server\IoServer::factory( new Ratchet\WebSocket\WsServer(new Server), 7890 )->run();
30 minutes. WEBSITE: ok thanks. SERVER: you there, you are not doing anything. generate this report. WORKER1: ok i’m off to work on it. bbl. // 30 min later WORKER1: all done. website can view it whenever. SERVER: ok thanks. i’ll email that bloke.
servers need to know how to handle: connections, data inputs, disconnections. clients need to know how to handle: data inputs, disconnections. both need to be able to: send data to the other.