JDK Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 4.32, 2006

Socket Communication

Part:   1  2   3  4 

JDK Tutorials - Herong's Tutorial Notes © Dr. Herong Yang

Internationalization

Character Set and Encoding

Socket Communication

Document Object Model (DOM)

XSD Validation in Java

XSL - Transformer in Java

JCA - Private and Public Key Pairs

JCE - Secret Key

SSL (Secure Socket Layer)

SSL - Client Authentication

... Table of Contents

(Continued from previous part...)

The following diagram shows the steps involved in establishing a two-way communication link using the methods provided by ServerSocket and Socket classes:

       Client System            Server System
       Internet Address #a      Internet Address #b
Step   Available Port #p        Available Port #q
1                               ss = new ServerSocket()
2                               ss.bind(#b+#q) 
3                               Socket cs = ss.accept()
4      cs = new Socket()        (waiting)
5      cs.bind(#a+#p)           (waiting)
6      cs.connect(#b+#q)        (receiving request)
7      (estalishing the link)   (establishing the link)
8      (cs is ready)            (cs is ready)

ReverseEchoer - A Simple Server Socket Application

The following program called ReverseEchoer is a simple server socket application, which listens with a server socket for a connect request. Once connected, it reads what lines of text from the remote application, reverses the text lines, and echos back to the remote application:

/**
 * ReverseEchoer.java
 * Copyright (c) 2002 by Dr. Herong Yang
 */
import java.io.*;
import java.net.*;
public class ReverseEchoer {
   public static void main(String[] args) {
      try {
         ServerSocket s = new ServerSocket(8888);
         printServerSocketInfo(s);
         Socket c = s.accept();
         printSocketInfo(c);
         BufferedWriter w = new BufferedWriter(new OutputStreamWriter(
            c.getOutputStream()));
         BufferedReader r = new BufferedReader(new InputStreamReader(
            c.getInputStream()));
         String m = "Welcome to Reverse Echo Server."+
            " Please type in some words.";
         w.write(m,0,m.length());
         w.newLine();
         w.flush();
         while ((m=r.readLine())!= null) {
            if (m.equals(".")) break;
            char[] a = m.toCharArray();
            int n = a.length;
            for (int i=0; i<n/2; i++) {
               char t = a[i];
               a[i] = a[n-1-i];
               a[n-i-1] = t;
            }
            w.write(a,0,n);
            w.newLine();
            w.flush();
         }
         w.close();
         r.close();
         c.close();
         s.close();
      } catch (IOException e) {
         System.err.println(e.toString());
      }
   }
   private static void printSocketInfo(Socket s) {
      System.out.println("Remote address = "
         +s.getInetAddress().toString());
      System.out.println("Remote port = "
         +s.getPort());
      System.out.println("Local socket address = "
         +s.getLocalSocketAddress().toString());
      System.out.println("Local address = "
         +s.getLocalAddress().toString());
      System.out.println("Local port = "
         +s.getLocalPort());
   }
   private static void printServerSocketInfo(ServerSocket s) {
      System.out.println("Server socker address = "
         +s.getInetAddress().toString());
      System.out.println("Server socker port = "
         +s.getLocalPort());
   } 
}

Note that:

  • The ServerSocket object, s, instantiated in this program is bound to the Internet address of the computer system on which it is running. The port number, 8888, in this binding is supplied as a parameter to constructor.
  • Socket.getInputStream() and Socket.getOutputStream() are used to create an input stream and output stream, so the application program can talk to the remote applicaton through the socket object.
  • If a text line received only contains a single character '.', the communication link will be terminated by the Socket.close() method.

Run ReverseEchoer, you will get the following output on the console window:

Server socker address = 0.0.0.0/0.0.0.0
Server socker port = 8888

This tells us that the program is listening at address 0.0.0.0 and port 8888.

To test ReverseEchoer, we can use the an existing client program called telnet to initiate the communucation request and talk to ReverseEchoer. Open another command window and type in the following command:

telnet 127.0.0.1 8888

Immediately, you will more output on the console window of ReverseEchoer:

Remote address = /127.0.0.1
Remote port = 1068
Local socket address = /127.0.0.1:8888
Local address = /127.0.0.1
Local port = 8888

This tells us that the server socket received a connection request, and a communication link has be established with the remote application, which the telnet program running on the same machine. The local address and remote address are the same, 127.0.0.1. The remote port is 1068, which is picked up by the telnet program.

(Continued on next part...)

Part:   1  2   3  4 

Dr. Herong Yang, updated in 2006
JDK Tutorials - Herong's Tutorial Notes - Socket Communication