ReverseEchoer.java - A Simple Server Socket Application

This section provides a tutorial example on how to write a network application, ReverseEchoer.java, that creates a server socket and listens for remote connection requests.

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 lines of text from the remote application, reverses the text lines, and echoes back to the remote application:

/* ReverseEchoer.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
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 socket address = "
         +s.getInetAddress().toString());
      System.out.println("Server socket port = "
         +s.getLocalPort());
   }
}

Note that:

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

herong> java ReverseEchoer.java

Server socket address = 0.0.0.0/0.0.0.0
Server socket 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 existing client program called "telnet" to initiate the communication request and talk to ReverseEchoer. Open another command window and type in the following command:

herong> telnet 127.0.0.1 8888

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Welcome to Reverse Echo Server. Please type in some words.

Immediately, you will see 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.

In the telnet window, type in the following text:

Fish, I love you and respect you very much.
But I will kill you dead before this day ends.
.

The text will be reversed and returned back from the ReverseEchoer:

Welcome to Reverse Echo Server. Please type in some words.
.hcum yrev uoy tcepser dna uoy evol I ,hsiF
.sdne yad siht erofeb daed uoy llik lliw I tuB
.

Note that the telnet program is not displaying text you typed in. It only displays the text received from ReverseEchoer program.

Table of Contents

 About This JDK Tutorial Book

 JDK (Java Development Kit)

 Java Date-Time API

 Date, Time and Calendar Classes

 Date and Time Object and String Conversion

 Number Object and Numeric String Conversion

 Locales, Localization Methods and Resource Bundles

 Calling and Importing Classes Defined in Unnamed Packages

 HashSet, Vector, HashMap and Collection Classes

 Character Set Encoding Classes and Methods

 Character Set Encoding Maps

 Encoding Conversion Programs for Encoded Text Files

 Java Logging

Socket Network Communication

 What Is a Socket?

 Establishing a Socket Communication Link

ReverseEchoer.java - A Simple Server Socket Application

 SocketClient.java - A Simple Client Socket Application

 ReverseEchoServer.java - A Multi-Connection Socket Server

 Binding Sockets to Specific Ports

 Datagram Network Communication

 DOM (Document Object Model) - API for XML Files

 SAX (Simple API for XML)

 DTD (Document Type Definition) - XML Validation

 XSD (XML Schema Definition) - XML Validation

 XSL (Extensible Stylesheet Language)

 Message Digest Algorithm Implementations in JDK

 Private key and Public Key Pair Generation

 PKCS#8/X.509 Private/Public Encoding Standards

 Digital Signature Algorithm and Sample Program

 "keytool" Commands and "keystore" Files

 KeyStore and Certificate Classes

 Secret Key Generation and Management

 Cipher - Encryption and Decryption

 The SSL (Secure Socket Layer) Protocol

 SSL Socket Communication Testing Programs

 SSL Client Authentication

 HTTPS (Hypertext Transfer Protocol Secure)

 Outdated Tutorials

 References

 Full Version in PDF/EPUB