• home
  • forum
  • my
  • kt
  • download
  • XML in Client and Server Communication

    Author: 2007-08-10 11:47:49 From:

    This chapter describes:

    • Different XML client and server communication models.
    • XML and Socket Communication Example - GameServer.pl
    • XML and Socket Communication Example - GameClient.pl

    XML Client and Server Communication Model

    Once we know how to work XML strings and hashes, we can now look at how XML technology can be used in client and server communication.

    The most primitive way of using XML technology in client and server communication is to write a client program and a server program to send and receive XML messages with TCP socket communication over Internet. The following diagram illustrates how this works:

    Client System                         Server System
    
                 XML    |    Internet    |    XML
    Client Prog.<--->TCP|<-------------->|TCP<--->Server Prog.
    

    To learn more about TCP socket communication, see the "Socket Communication" chapter of this book.

    XML with Socket Communication Example - GameServer.pl

    In the following example, I wrote a simple client and server base game application. It's a simple game, in which the server accepts new clients, 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) 1999 by Dr. Herong Yang
    #
       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 STDIN to socket";
          open(STDOUT, "+>&NEWSOCK") || die "Die: Setting STDOUT to socket";
          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 quess.";
       } else {
          $msg = "Your guess is too low.\n Please make another quess.";
       }
       $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>
    

    XML with Socket Communication Example - GameClient.pl

    Now let's see a real client program, GameClient.pl:

    #- GameClient.pl
    #- Copyright (c) 1999 by Dr. Herong Yang
    #
       use Socket;
       use XML::Simple;
       &init;
       $ref = $xs->XMLin("game_1.xml");
       $ref = &send($ref);
       $gid = $ref->{s}->[0]->{i}->[0];
       $ref = $xs->XMLin("game_2.xml");
       $ref->{c}->[0]->{i}->[0] = $gid;
       $ref->{c}->[0]->{n}->[0] = "39";
       $ref = &send($ref);
       $ref = $xs->XMLin("game_2.xml");
       $ref->{c}->[0]->{i}->[0] = "-1";
       $ref->{c}->[0]->{n}->[0] = "29";
       $ref = &send($ref);
       exit;
    sub init {
       open(LOG,">> GameClient.log");
       select(LOG); $|=1;
       open(STDERR, ">&LOG") || die "Die: Setting STDERR to log file";
       open(REC,">> GameClient.rec");
       select(REC); $|=1;
       $xs = new XML::Simple(keeproot => 1, forcearray => 1, 
          searchpath => ".");
       $host = "localhost";
       $port = "8080";
    }
    sub send {
       my ($ref) = @_;
       socket(SOCK,PF_INET,SOCK_STREAM,'tcp');
    #   bind(SOCK, pack_sockaddr_in("1024", INADDR_ANY)); # no need to bind
       $sAddress = pack_sockaddr_in($port,inet_aton($host));
       connect(SOCK, $sAddress) || die "Die: Connecting to $host $port";
       open(STDIN, "+<&SOCK") || die "Die: Setting STDIN to socket";
       open(STDOUT, "+>&SOCK") || die "Die: Setting STDOUT to socket";
       select(STDOUT); $|=1;
       my $xml = $xs->XMLout($ref);
       print STDOUT $xml;
       print REC "$xml\n";
       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";
       close(STDIN);
       close(STDOUT);
       return $xs->XMLin($msg);
    }
    

    This client program is also simple. It reads some XML message files prepared a game, and send them over to the server one at a time. There are two XML message files:

    1. game_1.xml:

    <c><m>Hello</m></c>
    

    2. game_2.xml:

    <c><i>0</i><n>0</n></c>
    

    If you run the client program, you should get the following in the GameClient.rec recording file:

    a<c>
      <m>Hello</m>
    </c>
    
    <s>
      <m>Welcome to Game Server!
    I have a number between 0 and 99 for you to guess.</m>
      <i>1</i>
    </s>
    
    <c>
      <n>39</n>
      <i>1</i>
    </c>
    
    <s>
      <m>Your guess is too high.
     Please make another quess.</m>
      <i>1</i>
    </s>
    
    <c>
      <n>29</n>
      <i>-1</i>
    </c>
    
    <s>
      <m>Sorry. Your game ID doesn't exist.</m>
      <i>0</i>
    </s>
    

    This clearly shows you a simple conversation between the client and server with XML messages.

    discuss this topic to forum

    relation tutorial

    No relevant information

    New

    Hot