Socket reader in PHP. Second part

In the pre­vi­ous post I have showed how to cre­ate a socket reader in php step by step. So by some strange tra­di­tion now I’m going to rep­res­ent OOP vari­ant. In fact, this is a sand­box ver­sion of new adapter for Chroot­G­ate­way. :)) But it can be used any­where, without any prob­lems.

This class in fact is a simple wrap­per. It will only take care about listen­ing cycle. So cre­at­ing and and bind­ing socket is left sim­ilar to stand­ard pro­cess of cre­at­ing socket. As class has neces­sary doc­u­ment­a­tion, I’ll only show an example of it’s usage. First of all you’ll need to include it into your script:

require_once 'SocketServer.php';

Also, to use this server, you’ll need to pre­pare a hand­ler of requests. To stop server, hand­ler should return boolean false. To dis­con­nect cli­ent from server it should return NULL. Any else returned value will be returned as a response to cli­ent. So let’s cre­ate a simple hand­ler which will make server act exactly as it was on pre­vi­ous post.

function my_handler($request)
{
    if (1 === preg_match('/quit|exit/i', $request)) {
        return null;
    }

    if (1 === preg_match('/stop|halt/i', $request)) {
        return false;
    }

    return md5($request) . PHP_EOL;
}

Now I’m cre­at­ing a socket server with new SocketServer() which takes same argu­ments socket_create() does:

$server = new SocketServer(AF_INET, SOCK_STREAM, SOL_TCP);

After that we need to setHandler(), bind() socket and run() server:

$motd   = 'WELCOME TO THE SIMPLE SOCKET SERVER IN PHP' . "\n"
        . '------------------------------------------' . "\n";
$server -> bind('0.0.0.0', 12345);
$server -> setMotd($motd);
$server -> setHandler('my_handler');
$server -> run();

Also you can set a wel­come mes­sage with setMotd() method:

$motd   = 'WELCOME TO THE SIMPLE SOCKET SERVER IN PHP' . "\n"
        . '------------------------------------------' . "\n";
$server -> setMotd($motd);

Of course it can be done with chain­ing, as setHandler() and bind() are return­ing self reference:

$motd   = 'WELCOME TO THE SIMPLE SOCKET SERVER IN PHP' . "\n"
        . '------------------------------------------' . "\n";
$server -> bind('0.0.0.0', 12345)
        -> setMotd($motd)
        -> setHandler('my_handler')
        -> run();

On any error, Excep­tion will be thrown. So you can use try-catch to dis­play exception’s mes­sage (e.g. $e->getMessage()) and return cor­res­pond­ing error code. Now it’s time to com­bine all pieces in one place:

< ?php
/**
 * SocketServer
 *
 * This file is part of SocketServer.
 *
 * SocketServer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SocketServer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SocketServer. If not, see .
 *
 * @package SocketServer
 * @link http://blog.ixti.ru/?p=107 Socket reader in PHP. Second part
 * @copyright Copyright (c) 2009 Aleksey V. Zapparov AKA ixti 
 * @license http://www.gnu.org/licenses/ GPLv3
 */

/**
 * SocketServer
 */
require_once 'SocketServer.php';

// Handler function
function my_handler($request)
{
    if (1 === preg_match('/quit|exit/i', $request)) {
        return null;
    }

    if (1 === preg_match('/stop|halt/i', $request)) {
        return false;
    }

    return md5($request) . PHP_EOL;
}

try {
    $motd   = 'WELCOME TO THE SIMPLE SOCKET SERVER IN PHP' . "\n"
            . '------------------------------------------' . "\n";
    $server = new SocketServer(AF_INET, SOCK_STREAM, SOL_TCP);
    $server ->bind('0.0.0.0', 12345)
            ->setMotd($motd)
            ->setHandler('my_handler')
            ->run();
    exit(0);
} catch (Exception $e) {
    fwrite(STDERR, $e->getMessage() . PHP_EOL);
    exit(1);
}
  • del.icio.us
  • Google Bookmarks
  • Identi.ca
  • Twitter
  • Technorati
  • Digg
  • Slashdot
  • Facebook
  • MisterWong
  • Reddit
  • StumbleUpon
  • Mixx
  • HelloTxt
  • LinkedIn
  • PDF
  • email
  • Print
This entry was posted in Development, Networking and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>