Recent Changes - Search:

Network Programming

This website demonstrates using wikis as teaching and learning tool.

The course instructor is happy to share the teaching materials here with those who find it readable.

Network Programming in Java - Part Two

A Network Programming Lecture by Steven Choy

Lecture Overview: Develop server-side programs using sockets and streams - Using the ServerSocket class - General operations of server program - Daytime Server Program in Java - Building an echo server


Develop server-side programs using sockets and streams

  • To implement a server program, we use the ServerSocket class as well as the Socket class.
  • The purpose of the ServerSocket class is to receive TCP/IP connections requests from remote clients.
  • The basic procedure for implementing a server is to open a ServerSocket on a particular port number, and then listen for client connections.
  • When a client connects, the server creates a Socket object.
  • The server then uses this socket in the same manner as the client – it uses the Socket to extract an InputStream and an OutputStream and then communicate with the client through the stream’s interface.

Using the ServerSocket class

  • Receive connection requests from remote clients
  • Constructors and main methods
ServerSocket(int port) throws IOException;

ServerSocket(int port, int backlog) throws IOException;

ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException;

Socket accept() throws IOException;

void close() throws IOException;

InetAddress getInetAddress();

int getLocalPort();
  • Explanations:
You use its constructor to open a ServerSocket on a particular local port number for listening for the client connection.
You then use its accept() method to obtain a Socket for each client connection.
Before a client contacts the server, the server is blocked to listen for a client connection.
After that, you use the facilities of Socket to communicate with the connected clients.
When you no longer need a ServerSocket, you invoke its close() method.
  • Summary of the key API of the ServerSocket class:
ServerSocket(int port), ServerSocket(int port, int backlog) – creates s server socket that is bound to the specified local port. The optional backlog is the maximum number of incoming connection that can be queued.
Socket accept() – listens for and accepts an incoming connection to this server socket and accept it, and returns a newly created Socket associated with the local end of the established connection. This method blocks until an incoming connection arrives.
void close() – closes this server socket.
InetAddress getInetAddress(), int getLocalPort() – returns the local address or port of this server socket.
boolean isClosed() – tests if this server socket is closed.

Socket Server - general operations

1. Open a ServerSocket with a port
2. Loop forever
Accept a connection to create a Socket
Start a thread to handle the client
The client handling thread obtains streams from the socket and read/write the streams

Case Study 1: Daytime Server Program in Java

import java.net.*;
import java.io.*;
import java.util.Date;

public class DaytimeServer {

  public final static int DEFAULT_PORT = 13;

  public static void main(String[] args) {

   int port = DEFAULT_PORT;
   if (args.length > 0) {
     try {
        port = Integer.parseInt(args[0]);
        if (port < 0 || port >= 65536) {
          System.out.println("Port must between 0 and 65535");
          return;
        }
     }
     catch (NumberFormatException ex) {
       // use default port
     }

   }

   try {

     ServerSocket server = new ServerSocket(port);

     Socket connection = null;
     while (true) {

       try {
         connection = server.accept();
         Writer out = new OutputStreamWriter(connection.getOutputStream());
         Date now = new Date();
         out.write(now.toString() +"\r\n");
         out.flush();
         connection.close();
       }
       catch (IOException ex) {}
       finally {
         try {
           if (connection != null) connection.close();
         }
         catch (IOException ex) {}
       }

     }  // end while

   }  // end try
   catch (IOException ex) {
     System.err.println(ex);
   } // end catch

  } // end main

} // end DaytimeServer
  • Class exercise: compile, run, and test the server program.

Case Study 2: Building an echo server

  • An echo server is a server that returns, or echoes, whatever it receives from a client back to the client.
  • It can be used for network access testing and performance measuring. The protocol uses the default port of 7, and is described in RFC 862.
  • Version 1: a simple server that handles only one client connection and then quits
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EchoServer1 {

    private static Logger logger = Logger.getLogger("EchoServer1");

    public static void main(String[] args) {
        int port = args.length > 0 ? Integer.parseInt(args[0]) : 7;
        try {
            ServerSocket server = new ServerSocket(port);
            Socket socket = server.accept();
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
            int data; // a byte of data
            while ((data = is.read()) != -1) // read gives -1 on end of stream
                os.write(data);
            socket.close();
            server.close();
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }
}
Class exercise: compile, run, and test the above server program.
  • Version 2: a server that handles multiple connections sequentially
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EchoServer2 {

    private static Logger logger = Logger.getLogger("EchoServer2");

    public static void main(String[] args) {
        int port = args.length > 0 ? Integer.parseInt(args[0]) : 7;
        try {
            ServerSocket server = new ServerSocket(port);
            logger.info("Server started, listening at port " + port + " ...");
            while (true) {
                Socket socket = server.accept();
                logger.info("Accepted client " + socket.getInetAddress() +
                        ":" + socket.getPort());
                InputStream is = socket.getInputStream();
                OutputStream os = socket.getOutputStream();
                int data; // a byte of data
                while ((data = is.read()) != -1) // -1 on end of stream
                    os.write(data);
                socket.close();
                logger.info("Disconnected client " + socket.getInetAddress() +
                        ":" + socket.getPort());
            }
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }
}
Class exercise: compile, run, and test the above server program.
  • Version 3: a multi-threaded server that can handle multiple connections concurrently
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EchoServer3 {

    private static Logger logger = Logger.getLogger("EchoServer3");

    /** Handler for an individual client */
    static class ClientHandler implements Runnable {
        private Socket socket;

        ClientHandler(Socket socket) {
            this.socket = socket;
        }

        /** Perform echoing to the client socket */
        public void run() {
            logger.info("Accepted client " + socket.getInetAddress() + ":"
                    + socket.getPort());
            try {
                InputStream is = socket.getInputStream();
                OutputStream os = socket.getOutputStream();
                int data; // a byte of data
                while ((data = is.read()) != -1) // -1 on end of stream
                    os.write(data);
                socket.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
            }
            logger.info("Disconnected client " + socket.getInetAddress() + ":"
                    + socket.getPort());
        }
    }

    public static void main(String[] args) {

        int port = args.length > 0 ? Integer.parseInt(args[0]) : 7;
        try {
            ServerSocket server = new ServerSocket(port);
            logger.info("Server started, listening at port " + port + " ...");
            ExecutorService executor = Executors.newCachedThreadPool();
            while (true) {
                Socket socket = server.accept();
                ClientHandler handler = new ClientHandler(socket);
                executor.execute(handler);
            }
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }
}
Class exercise: compile, run, and test the above server program.

Java Daytime client program for you to test the server

import java.net.*;
import java.io.*;
import java.util.*;

public class DayTimeClient {
  static int dayTimePort = 13;

  public static void main(String args[]) {
    try {
      Socket sock = new Socket(args[0], dayTimePort);
      BufferedReader din = new BufferedReader(
        new InputStreamReader(sock.getInputStream()));
      String rTime = din.readLine();
      System.out.println(rTime);
      sock.close();
    }
    catch (Exception e) {}
  }
}

Can you write a Java client program to test the echo server?


Java Programming Lesson for this lecture

  • Java multithreading
  • Java Exception handling
  • What is Java interface?

I will cover these topics in our other lectures.


Thanks for Reading

If you would rather like to have this lecture note in printed format, please click the print action link in the top right corner.

If you find any problem in this lecture note, please feel free to tell Steven via steven@findaway.hk.

Edit - History - Print - Recent Changes - Search
Page last modified on October 12, 2009, at 03:24 PM