NotionCommotion Posted March 17, 2017 Share Posted March 17, 2017 (edited) I am trying to emit an error and have the server receive it. A couple of issues. Guess I was thinking that $stream->on('error',.. and $client->on('error',... will receive different emits. They don't seem to do so. Does the below code make no sense in the regard, and should I be doing things differently? Maybe just emit "criticalError" and "normalError", and have server's on listen for both? Should the ->on() be on $stream or $client? Is $this->socket->on('error', function($error){ ...}); necessary in LengthPrefixStream()? What does it do if it is there? Thanks <?php $loop = \React\EventLoop\Factory::create(); // Or \React\EventLoop\StreamSelectLoop()? $socket = new \React\Socket\Server($loop); $socket->on('connection', function (\React\Socket\ConnectionInterface $stream) { $client = new LengthPrefixStream($stream); $client->on('data', function($data) use ($client){ syslog(LOG_INFO,"on data"); }); $stream->on('error', function($error, $stream) { //Critical error, disconnect from server syslog(LOG_INFO,"on stream error: ".json_encode($error)); $stream->close(); }); $client->on('error', function($error) use($stream){ //Non-Critical error, Do not disconnect from server syslog(LOG_INFO,"on client error: ".json_encode($error)); }); }); $socket->listen($this->host['port'],$this->host['url']); $loop->run(); <?php class LengthPrefixStream implements EventEmitterInterface { use EventEmitterTrait; private $socket=false; public function __construct(DuplexStreamInterface $socket, $parseJson=1){ $this->parseJson = $parseJson; $this->socket = $socket; $this->socket->on('data', function($data){ //I will parse the stream, but am not showing it for this example $obj=json_decode($data); if (json_last_error() == JSON_ERROR_NONE){ $this->emit('data', [$obj]); } else { syslog(LOG_INFO,"Non-critical error. Do not disconnect from client."); $this->emit('error', ["Bad JSON"]); } }); $this->socket->on('error', function($error){ syslog(LOG_INFO,"Critical error. Disconnect from client."); $this->emit('error', [$error]); }); } } Edited March 17, 2017 by NotionCommotion Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.