After I have published SocketServer on PHPClasses.org, I received comments about some ugly places and ideas of improvement. So now, it can be used as a skeleton for something more interesting then “Hello, World!” sample. In this post I’ll guide you through modified example.php step by step as in previous one but with new functions and improvement of SocketServer in focus. So in fact it’s just an extension of previous post.
Since previous version, request handler setter’s name was changed from setHandler() to setRequestHandler(). Also, class has obtained three events (with corresponding handler setters):
- onOpen —
setOnOpenHandler() - onCleanup —
setOnCleanupHandler() - onClose —
setOnCloseHandler()
Now, let me introduce sample handlers for that events. First event, onOpen is fired upon new connection arrives. You can use it to have your registry of connections to decide which exact action should be handled according to specified (passed) request, connection id, remote address and remote port (in case of INET* sockets).
function my_open_handler($id, $addr, $port = null)
{
echo sprintf('New connection [%d] arrived from %s:%d', $id, $addr, $port) . "\n";
}
Second event onCleanup is called with only one argument passed — connection id, upon client shutdowned connection manually but server didn’t know about it.
function my_cleanup_handler($id)
{
echo sprintf('Connection [%d] cleaned-up', $id) . "\n";
}
And finally, third event onClose is similar to onClenup but called upon request handler asks to close this connection.
function my_close_handler($id)
{
echo sprintf('Connection [%d] closed', $id) . "\n";
}
Of course request handler now also receives connection id too. So here’s new example of request handler:
function my_handler($request, $id)
{
if (1 === preg_match('/quit|exit/i', $request)) {
return null;
}
if (1 === preg_match('/stop|halt/i', $request)) {
return false;
}
echo sprintf('*** Got "%s" from %d', $request, $id) . PHP_EOL;
return md5($request) . PHP_EOL;
}
After all was explained (hope so, if not — feel free to comment here or send me an email), all we need is to register necessary handlers just as it was with request handler. So you can download attached package to post (below) with class itself and example file.
UPD (26 October 2009) Since today all updated versions of class and it’s example will be placed on phpclasses.org.