Contents / Previous / Next


Java Server

Java server programs are based on the socket class.

Example SimpleEchoServer:

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

public class SimpleEchoServer
{
  public static void main(String[] args)
  {
    try {
      System.out.println("Waiting for connection on Port 7...");
      ServerSocket echod = new ServerSocket(7);
      Socket socket = echod.accept();
      System.out.println("Connected....");
      InputStream in = socket.getInputStream();
      OutputStream out = socket.getOutputStream();
      int c;
      while ((c = in.read()) != -1) {
        out.write((char)c);
        System.out.print((char)c);
      }
      System.out.println("Server closed Connection.");
      socket.close();
      echod.close();
    } catch (IOException e) {
      System.err.println(e.toString());
      System.exit(1);
    }
  }
}
Log in as root to start the server (normal users can only use ports > 1023):
> /usr/lib/java/bin/java SimpleEchoServer

Waiting for connection on Port 7...
After that the server is running you can open a telnet connection to the server (as a normal user in an other shell) :
> telnet localhost 7
Trying ::1...
Connected to localhost.
Escape character is '^]'.
hello me
hello me
^]
 
telnet> quit
Connection closed.
In the shell where you started the server as root it reports the successful connection and answers by echoing what you typed into the telnet. Later the server confirms the disconnection.
 
Connected....
hello me

Server closed Connection.