Writing a server


Last time, we talked about identifying the protocol the WorldsAway client and servers used to talk to each other.  So lets's see how easy it is to write a server using that protocol

There are almost as many programming languages suitable for writing server code as there are programmers who could write it.  Some languages are obtuse, some very clear. Some popular, some very niche.  Some have libraries to help you, others leave you to your own devices..

So, we'll have this discussion using ReactPHP, an event driven I/O framework for PHP.  PHP is not just for web pages; it has a powerful command-line option as well.  And it's simple to understand.

It doesn't take much to fire up a server listening on a port for incoming client connections -
$userServer = new Server(constant('LISTENIP').':'.constant('WORLDPORT'), $loop);
$userServer = new LimitingServer($userServer, MAXUSERS);

And then we need accept the connection and decide what to do with any data received.
$userServer->on('connection', function (ConnectionInterface $client) {
    $client->on('data', function ($data) {
while (strlen($data)) {
$cmd = unpack('nnoid/ncmdNum/NdataLen', $data);      $params = substr($data,8, $cmd['dataLen']);         // do something with the decoded packet $data = substr($data, 8 + $cmd['dataLen']); }     }); });

Notice how we used PHP's "unpack" command to pull the binary data out of the packet into individual variables.  This handles all the Big-Endian/Little-Endian issues for us.  We know that the numbers stored in the data come in big-bytes-first.  We don't really care just how our particular implementation of PHP stores them.

Once we've dealt with the received data, we generally need to respond to it.  This is equally simple. Here's a function to send a response
static function send($client, $noid, $ccode, $data)
{
        $len = strlen($data);
	$buf = pack("nnNa{$len}", $noid, $ccode, $len, $data);
	$client->write($buf);
	return true;
}

Here we use 'pack' to send the data back - the noid code, the command code, length of data block, and then the data.

 Next time ... deciphering the data ...

Comments

Popular Posts