GameServer.pl - XML Communication Server Example

This section provides a tutorial example on how write an XML communication server program to accept client connections, send and receive XML messages.

In the following example, I wrote a simple client and server based game application. It's a simple game, in which the server accepts new client connections, and holds a number for the client to guess.

The information is exchanged between the client and server in plain XML format, and delivered with plain TCP communication protocol.

Here is the server program, GameServer.pl:

#- GameServer.pl
#- Copyright (c) HerongYang.com. All Rights Reserved.
#
   use Socket;
   use XML::Simple;
   $xs = new XML::Simple(keeproot => 1, forcearray => 1);
   $gameID = 0;
   $number = 0;
   $response = "<s><i>0</i><m>hello</m></s>";
   &runServer;
   exit;
sub runServer {
   open(LOG,">> GameServer.log");
   select(LOG); $|=1;
   open(STDERR, ">&LOG") || die "Die: Setting STDERR to log file";
   open(REC,">> GameServer.rec");
   select(REC); $|=1;
   socket(SOCK,PF_INET,SOCK_STREAM,'tcp');
   bind(SOCK, pack_sockaddr_in("8080", INADDR_ANY));
   listen(SOCK, 1); # can only take one client at a time
   print LOG localtime().": Listening to port 8080\n";
   for (;;) {
      $cAddress = accept(NEWSOCK,SOCK) || die "Error: Accepting: $!";
      ($cPort, $cHost) = unpack_sockaddr_in($cAddress);
      $cHostName = inet_ntoa($cHost);
      print LOG localtime().": Connected with $cHostName at $cPort\n";
      open(STDIN, "+<&NEWSOCK") || die "Die: Setting socket STDIN";
      open(STDOUT, "+>&NEWSOCK") || die "Die: Setting socket STDOUT";
      select(STDOUT); $|=1;
      &serve;
      close(STDIN);
      close(STDOUT);
   }
}
sub serve {
   my ($tag,$fin,$msg);
   while (<STDIN>) {
      /<(\w+)>/ && ($tag=$1) unless $tag;
      /<\/$tag>/ && ($fin=$tag) if $tag;
      $msg = $msg.$_;
      last if $fin;
   }
   print REC "$msg\n";
   my $ref = $xs->XMLin($msg);
   if (exists($ref->{c}->[0]->{i})) {
      my $gid = $ref->{c}->[0]->{i}->[0];
      my $num = $ref->{c}->[0]->{n}->[0];
      if ($gid == $gameID) {
         $msg = &oldGame($gid,$num);
      } else {
         $msg = &invalidGame($gid,$num);
      }
   } else {
      $msg = &newGame;
   }
   print STDOUT $msg;
   print REC "$msg\n";
}
sub oldGame {
   my ($gid,$num) = @_;
   my $ref = $xs->XMLin($response);
   my $msg;
   if ($num == $number) {
      $msg = "Congratulations!\n"
         ."I have another number between 0 and 99 for you to guess.";
      $gameID++;
      $number = rand(100);
   } elsif ($num > $number) {
      $msg = "Your guess is too high.\n Please make another guess.";
   } else {
      $msg = "Your guess is too low.\n Please make another guess.";
   }
   $ref->{s}->[0]->{i}->[0] = $gameID;
   $ref->{s}->[0]->{m}->[0] = $msg;
   return $xs->XMLout($ref);
}
sub newGame {
   $gameID++;
   $number = rand(100);
   my $ref = $xs->XMLin($response);
   $ref->{s}->[0]->{m}->[0] = "Welcome to Game Server!\n"
      ."I have a number between 0 and 99 for you to guess.";
   $ref->{s}->[0]->{i}->[0] = $gameID;
   return $xs->XMLout($ref);
}
sub invalidGame {
   my ($sid,$num) = @_;
   my $ref = $xs->XMLin($response);
   $ref->{s}->[0]->{m}->[0] = "Sorry. Your game ID doesn't exist.";
   return $xs->XMLout($ref);
}

The game ID concept is used to identify if an incoming XML message is for continuing an existing game or starting a new game. When the server receives a client message for the first time, it will assign a new game ID, and return the game ID to the client. The client program must use this game ID in the subsequent messages to continue the same game.

The server is not written to serve multiple clients simultaneously.

Let's run GameServer.pl in command window, and let it listen to port 8080 for any client program connection.

Now in another command window, we can run the telnet command to test the server, "telnet localhost 8080". Then enter the following XML message to the telnet program. Remember telnet will not echo your input on the screen, so you have to type in the message "blindly".

<c><m>Hi there!</m></c>

You will get the following message from the server displayed on the telnet window

<s>
     <m>Welcome to Game Server!
          I have a number between 0 and 99 for you to guess
.</m>
       <i>2</i>
               </s>

Table of Contents

 About This Book

 Perl on Linux Systems

 ActivePerl on Windows Systems

 Data Types: Values and Variables

 Expressions, Operations and Simple Statements

 User Defined Subroutines

 Perl Built-in Debugger

 Name Spaces and Perl Module Files

 Symbolic (or Soft) References

 Hard References - Addresses of Memory Objects

 Objects (or References) and Classes (or Packages)

 Typeglob and Importing Identifiers from Other Packages

 String Built-in Functions and Performance

 File Handles and Data Input/Output

 Open Files in Binary Mode

 Open Directories and Read File Names

 File System Functions and Operations

 Image and Picture Processing

 Using DBM Database Files

 Using MySQL Database Server

 Socket Communication Over the Internet

 XML::Simple Module - XML Parser and Generator

XML Communication Model

 XML Messages over Socket Connections

GameServer.pl - XML Communication Server Example

 GameClient.pl - XML Communication Client Example

 SOAP::Lite - SOAP Server-Client Communication Module

 Perl Programs as IIS Server CGI Scripts

 CGI (Common Gateway Interface)

 XML-RPC - Remote Procedure Call with XML and HTTP

 RPC::XML - Perl Implementation of XML-RPC

 Integrating Perl with Apache Web Server

 CGI.pm Module for Building Web Pages

 LWP::UserAgent and Web Site Testing

 Converting Perl Script to Executable Binary

 Managing Perl Engine and Modules on macOS

 Archived Tutorials

 References

 Full Version in PDF/EPUB