How do I write a server socket that can handle input and output?
Author: Deron Eriksson
Description: This Java tutorial describes how write a server socket that can read input and write output.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.4


Creating a server to run on a particular port is very easy in JavaSW using the ServerSocket class, which you instantiate with the port number that you would like it to run on. The TestServerSocket class creates a ServerSocket object and then accepts connections to the server within an infinite 'while(true)' loop. It accepts connections to the server via the accept() method, which gives us a Socket object that we can read text from and write text to. Text is written to the output stream that is obtained from the socket, and text is read from the input stream.

TestServerSocket.java

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServerSocket {

	public static void main(String args[]) throws IOException {
		final int portNumber = 81;
		System.out.println("Creating server socket on port " + portNumber);
		ServerSocket serverSocket = new ServerSocket(portNumber);
		while (true) {
			Socket socket = serverSocket.accept();
			OutputStream os = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(os, true);
			pw.println("What's you name?");

			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String str = br.readLine();

			pw.println("Hello, " + str);
			pw.close();
			socket.close();

			System.out.println("Just said hello to:" + str);
		}
	}
}

If we start up the TestServerSocket class in EclipseSW, we see that the server socket has been started up on port 81.

TestServerSocket output displayed in console

We can test our server by opening a command prompt window and typing 'telnet localhost 81'.

telnet localhost 81

The server asks us our name, so I typed 'Bob'. It says 'Hello, Bob' and then closes the connection.

Interaction with TestServerSocket via telnet

In the console window in Eclipse, we can see the 'Just said hello to:Bob' message has appeared.

TestServerSocket output displayed in console

In the command prompt window, once again let's telnet to the localhost on port 81.

telnet localhost 81

This time, I answered 'Fred', and the server says 'Hello, Fred' and closes the connection.

Interaction with TestServerSocket via telnet

In the Eclipse console window, we can see that 'Just said hello to:Fred' has appeared in the console output.

TestServerSocket output displayed in console

As you can imagine, by building upon the ServerSocket class, we could very easily create a rudimentary HTTP server without too much work.