Understanding Java: Simplified Hello World for Socket Programming

By Angsuman Chakraborty, Gaea News Network
Saturday, 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.

Discussion

Aruna
June 3, 2010: 11:41 pm

How to write java socket programs using Simplified API?

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :