Client – Server application using socket

Java provides three different strategies for client – server communication system. These are sockets, Remote Procedure Calls (RPC’s) and Java Remote Method Invocation (RMI). In this tutorial we are just sharing example code of sockets base client server system where server listens for client request at 8080 port and write back current date of server.

Server code

package socket;

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

public class CommServer {
	public static void main(String[] args) {
		try {
			// Listen for connection at 8080 socket
			ServerSocket sock = new ServerSocket(8080);

			while (true) {
				Socket client = sock.accept();
				PrintWriter pout = new PrintWriter(client.getOutputStream(),
						true);
				// write the Date to the socket
				pout.println(new java.util.Date().toString());
				// close the socket and resume
				// listening for connections
				client.close();
			}
		} catch (IOException ioe) {
			System.err.println(ioe);
		}
	}
}

Client code

package socket;

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

public class CommClient {

	public static void main(String[] args) {
		try {
			// make connection to server socket
			Socket sock = new Socket("localhost", 8080);
			InputStream in = sock.getInputStream();
			BufferedReader bin = new BufferedReader(new InputStreamReader(in));
			// read the date from the socket
			String line;
			while ((line = bin.readLine()) != null)
				System.out.println(line);
			// close the socket connection
			sock.close();
		} catch (IOException ioe) {
			System.err.println(ioe);
		}
	}
}

No Responses