Java facilities for networking

count problem

 To illustrate basic Java networking will use a simple client/server architecture. It comprises a server that maintains a variable count, and  number of clients, who can access the server and ask to set or increment the variable.

In this part, we will analyze how to implement this application using sockets. Later, we will see the same implemented using RMI, CORBA and mobile agents.

package java.net

    package java.net.DatagramSocket

    package java.net.ServerSocket

    package java.net.Socket

Datagram version of count

Scenario

Client code

package SocketDatagram;
import java.net.*;
import java.io.*;

public class Client
{ public static void main(String args[])
  {
    byte[] buffer = new byte[10];
    String sumString = "";
    String myOperation;
    DatagramPacket inPacket = null;
    DatagramPacket outPacket = null;

    try
    { if(args.length != 2)
      {
        System.out.println("Usage java Client <host> <count>");
        return;
      }

      // Create datagram socket
      DatagramSocket datagramSocket = new DatagramSocket(250);

      // Get inet addr of server
      InetAddress addr = InetAddress.getByName(args[0]);

      // set sum to zero
      System.out.println("Setting sum to 0");
      myOperation = "set_sum";
      myOperation.getBytes(0, myOperation.length(), buffer, 0);
      outPacket = new DatagramPacket(buffer, myOperation.length(),
                                  addr, 251);
      datagramSocket.send(outPacket);
      inPacket = new DatagramPacket(buffer, buffer.length);
      datagramSocket.receive(inPacket);
      buffer = inPacket.getData();
      sumString = new String(buffer, 0, 0, inPacket.getLength());
      System.out.println("sum = " + sumString);

      // get count, initialize start time
      System.out.println("Incrementing");
      int count = new Integer(args[1]).intValue();
      long startTime = System.currentTimeMillis();

      // perform increment "count" number of times
      for(int i = 0; i < count; i++)
      { myOperation = "increment";
        myOperation.getBytes(0, myOperation.length(), buffer, 0);
        outPacket = new DatagramPacket(buffer, myOperation.length(),
                                    addr, 251);
        datagramSocket.send(outPacket);
        inPacket = new DatagramPacket(buffer, buffer.length);
        datagramSocket.receive(inPacket);
        buffer = inPacket.getData();
        sumString = new String(buffer, 0, 0, inPacket.getLength());
      }

      // display statistics
      long stopTime = System.currentTimeMillis();
      System.out.println("Avg Ping = "
             +  ((stopTime - startTime) / (float)count) + " msecs");
      System.out.println("Sum = " + sumString);
    }
    catch(Exception e)
    { System.err.println(e);
    }
   }
}

Server code

package SocketDatagram;
import java.net.*;
import java.io.*;

public class Server
{ public static void main(String[] args)
  {
    byte[] buffer = new byte[10];
    int sum = 0;
    String sumString = "";
    DatagramSocket datagramSocket = null;
    DatagramPacket inPacket = null;
    DatagramPacket outPacket = null;
    InetAddress addr = null;

    try
    { // create socket
      datagramSocket = new DatagramSocket(251);

      // wait for request packets
      System.out.println("Waiting for client requests");

      // execute client requests
      while(true)
      {
        inPacket = new DatagramPacket(buffer, buffer.length);
        datagramSocket.receive(inPacket);
        buffer = inPacket.getData();
        addr   = inPacket.getAddress();   // addr for reply packet

        String myOperation = new String(buffer, 0, 0,
                                        inPacket.getLength());

        // perform increment operation
        if (myOperation.equals("increment"))
           sumString = String.valueOf(++sum);
        else
           // perform set sum operation
           if(myOperation.equals("set_sum"))
           { sum = 0;
             sumString = String.valueOf(sum);
             System.out.println("Sum = " + sumString);
           }

        sumString.getBytes(0, sumString.length(), buffer, 0);
        outPacket = new DatagramPacket(buffer, sumString.length(),
                                    addr, 250);
        datagramSocket.send(outPacket);
      }
    } catch (Exception e)
    { System.err.println("Closing DatagramSocket");
      if (datagramSocket != null)
         datagramSocket.close();
    }
  }
}

Buffered-stream socket versions of count

Client side


 

Client's code

package SocketBuffered;
import java.net.*;
import java.io.*;

public class Client
{ public static void main(String args[])
  { byte[] buffer = new byte[10]; // buffer for sockets transfers
    int bytesRead;                // variable for bytes read
    String sumString = "";        // variable for storing current sum
    String myOperation;           // variable for byte to string conversion

    try
    { if(args.length != 2)
      {
        System.out.println("Usage java Client <host> <count>");
        return;
      }

      // Create socket connection
      System.out.println("Opening socket and creating streams.");
      String host = args[0];
      Socket socket = new Socket(host, 250);

      // create streams
      BufferedOutputStream ostream = new BufferedOutputStream(socket.getOutputStream());
      BufferedInputStream istream = new BufferedInputStream(socket.getInputStream());

      // set sum to zero
      System.out.println("Setting sum to 0.");
      myOperation = "set_sum";
      myOperation.getBytes(0, myOperation.length(), buffer, 0);
      ostream.write(buffer, 0, myOperation.length());
      ostream.flush();
      bytesRead = istream.read(buffer, 0, 10);
      sumString = new String(buffer, 0, 0, bytesRead);

      // get count, initialize start time
      System.out.println("Incrementing.");
      int count = new Integer(args[1]).intValue();
      long startTime = System.currentTimeMillis();

      // perform increment "count" number of times
      for(int i = 0; i < count; i++)
      { myOperation = "increment";
        myOperation.getBytes(0, myOperation.length(), buffer, 0);
        ostream.write(buffer, 0, myOperation.length());
        ostream.flush();
        bytesRead = istream.read(buffer, 0, 10);
        sumString = new String(buffer, 0, 0, bytesRead);
      }

      // display statistics
      long stopTime = System.currentTimeMillis();
      System.out.println("Avg Ping = "
                        +  ((stopTime - startTime) / (float)count) + " msecs");
      System.out.println("Sum = " + sumString);
    }
    catch(Exception e)
    { System.err.println(e);
    }
   }
}

Server side

Server's code

package SocketBuffered;
import java.net.*;
import java.io.*;

public class Server
{ public static void main(String[] args)
  {
    Socket socket = null;
    byte[] buffer = new byte[10];  // buffer for sockets transfers
    int bytesRead;                 // bytes read to/from buffer
    int sum = 0;                   // current sum value
    String sumString = "";         // for byte to string conversion

    while (true)
    { try
      { // create socket
        ServerSocket serverSocket = new ServerSocket(250);

        // wait for connection then create streams
        System.out.println("Waiting for client connection");
        socket = serverSocket.accept();
        BufferedOutputStream ostream =
            new BufferedOutputStream(socket.getOutputStream());
        BufferedInputStream istream =
            new BufferedInputStream(socket.getInputStream());

        // execute client requests
        while(true)
        { bytesRead = istream.read(buffer, 0, 10);
          String myOperation = new String(buffer, 0, 0, bytesRead);

          // perform increment operation
          if(myOperation.equals("increment"))
             sumString = String.valueOf(++sum);
          else
             // perform set sum operation
             if(myOperation.equals("set_sum"))
             { sum = 0;
               sumString = String.valueOf(sum);
               System.out.println("Sum = " + sumString);
             }

          sumString.getBytes(0, sumString.length(), buffer, 0);
          ostream.write(buffer, 0, sumString.length());
          ostream.flush();
        }
      } catch (Exception e)
      { System.err.println("Closing Socket connection.");
        if (socket != null)
           try
           { socket.close();
           } catch (IOException ex) {}
      }
    }
  }
}

Data-stream socket version of count

Scenario

Same as for the version with buffer-streams.

Client's code

package SocketDataStream;
import java.net.*;
import java.io.*;

public class Client
{ public static void main(String args[])
  {
    String sumString = "";        // variable for storing current sum

    try
    { if(args.length != 2)
      {
        System.out.println("Usage java Client <host> <count>");
        return;
      }

      // Create socket connection
      System.out.println("Opening socket and creating streams.");
      String host = args[0];
      Socket socket = new Socket(host, 250);

      // create streams
      DataOutputStream ostream =
           new DataOutputStream(socket.getOutputStream());
      DataInputStream istream =
           new DataInputStream(socket.getInputStream());

      // set sum to zero
      System.out.println("Setting sum to 0.");
      ostream.writeUTF("set_sum");
      ostream.flush();
      sumString = istream.readUTF();

      // get count, initialize start time
      System.out.println("Incrementing.");
      int count = new Integer(args[1]).intValue();
      long startTime = System.currentTimeMillis();

      // perform increment "count" number of times
      for(int i = 0; i < count; i++)
      { ostream.writeUTF("increment");
        ostream.flush();
        sumString = istream.readUTF();
      }

      // display statistics
      long stopTime = System.currentTimeMillis();
      System.out.println("Avg Ping = "
                        +  ((stopTime - startTime) / (float)count) + " msecs");
      System.out.println("Sum = " + sumString);
    }
    catch(Exception e)
    { System.err.println(e);
    }
   }
}

Server's code

package SocketDataStream;
import java.net.*;
import java.io.*;

public class Server
{ public static void main(String[] args)
  {
    Socket socket = null;
    int sum = 0;                   // current sum value
    String sumString = "";

    while (true)
    { try
      { // create socket
        ServerSocket serverSocket = new ServerSocket(250);

        // wait for connection then create streams
        System.out.println("Waiting for client connection");
        socket = serverSocket.accept();
        DataOutputStream ostream =
            new DataOutputStream(socket.getOutputStream());
        DataInputStream istream =
            new DataInputStream(socket.getInputStream());

        // execute client requests
        while(true)
        { String myOperation = istream.readUTF();

          // perform increment operation
          if(myOperation.equals("increment"))
             sumString = String.valueOf(++sum);
          else
             // perform set sum operation
             if(myOperation.equals("set_sum"))
             { sum = 0;
               sumString = String.valueOf(sum);
               System.out.println("Sum = " + sumString);
             }

          ostream.writeUTF(sumString);
          ostream.flush();
        }
      } catch (Exception e)
      { System.err.println("Closing Socket connection.");
        if (socket != null)
           try
           { socket.close();
           } catch (IOException ex) {}
      }
    }
  }
}

Broadcasting to Multiple Recipient

Working with URLs