Interacting with a Client

More commonly, a server needs to both read a client request and write a response. The following program reads whatever the client sends and then sends it back to the client. In short this is an echo server.

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


public class EchoServer {

  public final static int defaultPort = 2346;

  public static void main(String[] args) {
  
    int port = defaultPort;
    
    try {
      port = Integer.parseInt(args[0]);
    }
    catch (Exception ex) {
    }
    if (port <= 0 || port >= 65536) port = defaultPort;
    
    try {
      ServerSocket ss = new ServerSocket(port);
      while (true) {
        try {
          Socket s = ss.accept();
          OutputStream os = s.getOutputStream();
          InputStream is = s.getInputStream();
          while (true) {
            int n = is.read();
            if (n == -1) break;
            os.write(n);
            os.flush();
          }
        }
        catch (IOException ex) {
        }
      }
    }
    catch (IOException ex) {
      System.err.println(ex);
    }

  }
  
}

Here's a sample session:

% telnet utopia.poly.edu 2346
Trying 128.238.3.21...
Connected to utopia.poly.edu.
Escape character is '^]'.
test
test
credit
credit
this is a test 1 2 3 12 3
this is a test 1 2 3 12 3
^]
telnet> close
Connection closed.
% 

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 18, 1997