Understanding Java: Simplified Hello World for Socket Programming
By Angsuman Chakraborty, Gaea News NetworkSaturday, April 15, 2006
In my experience much of the complexities a newcomer faces in the Java world is understanding extraneous stuff like handling exceptions or formatting data etc.
Today I was requested for the nth time (n -> infinity) how to write a simple socket client and server (actually debug one). Java tutorial is good but it is not simple. This is a very simple example of a Echo server and client. It minimally handles extraneous stuff to give simplicity to the procedure.
EchoClient.java
import java.net.*; import java.io.*; // Connects to port 6500 of specified host, // sends the message and prints the reply public class EchoClient { // Run as: java EchoClient hostname message public static void main(String args[]) throws Exception { Socket socket = new Socket(args[0], 6500); BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintStream ps = new PrintStream(socket.getOutputStream()); ps.println(args[1]); // Write message to socket // Print response from server System.out.println("Received: " + br.readLine()); socket.close(); } }
EchoServer.java
import java.net.*; import java.io.*; // Listens for connection on port 6500, // receives messages and echoes them back public class EchoServer { public static void main(String args[]) throws Exception { ServerSocket server = new ServerSocket(6500); Socket socket = null; while(true) { socket = server.accept(); BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintStream ps = new PrintStream( socket.getOutputStream()); ps.println(br.readLine()); // Echo input to output socket.close(); } } }
In the end it is a simple thing done simply. It doesn’t cover all the bases like clean exception handling or handling connections in parallel. Those should be left as later exercises when the developer is feeling more at ease with the language.
Aruna