Client Server Socket example in Java

  • 13 January 2017
  • ADM

 

Client Server Socket example in Java - images/logos/java.jpg

 

Sockets provide the communication mechanism between two computers using TCP. TCP is a two-way communication protocol.The java.net.Socket class represents the socket between the client and the server, and the java.net.ServerSocket class provides a mechanism for the server application to listen to clients and establish connections with them.

There are two important classes to be used for socket communication in java. The java.net.Socket class represents the socket between the client and the server, and the java.net.ServerSocket class provides a mechanism for the server application to listen to clients and establish connections with them.

Example

Server

Here is the example of the server side. The server will allow multiple connections. The server functionalities are simple, will just reply the message received back to the client.

package com.admfactory.io.socket;

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

public class SocketServer extends Thread {
	public static final int PORT_NUMBER = 8081;

	protected Socket socket;

	private SocketServer(Socket socket) {
		this.socket = socket;
		System.out.println("New client connected from " + socket.getInetAddress().getHostAddress());
		start();
	}

	public void run() {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = socket.getInputStream();
			out = socket.getOutputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String request;
			while ((request = br.readLine()) != null) {
				System.out.println("Message received:" + request);
				request += '\n';
				out.write(request.getBytes());
			}

		} catch (IOException ex) {
			System.out.println("Unable to get streams from client");
		} finally {
			try {
				in.close();
				out.close();
				socket.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		System.out.println("SocketServer Example");
		ServerSocket server = null;
		try {
			server = new ServerSocket(PORT_NUMBER);
			while (true) {
				/**
				 * create a new {@link SocketServer} object for each connection
				 * this will allow multiple client connections
				 */
				new SocketServer(server.accept());
			}
		} catch (IOException ex) {
			System.out.println("Unable to start server.");
		} finally {
			try {
				if (server != null)
					server.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}

Client

The client will read data from the console and will send it to the server on pressing Enter key. To quit the client you need to press q followed by Enter key.

package com.admfactory.io.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

	public static void main(String args[]) {
		String host = "127.0.0.1";
		int port = 8081;
		new Client(host, port);
	}

	public Client(String host, int port) {
		try {
			String serverHostname = new String("127.0.0.1");

			System.out.println("Connecting to host " + serverHostname + " on port " + port + ".");

			Socket echoSocket = null;
			PrintWriter out = null;
			BufferedReader in = null;

			try {
				echoSocket = new Socket(serverHostname, 8081);
				out = new PrintWriter(echoSocket.getOutputStream(), true);
				in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
			} catch (UnknownHostException e) {
				System.err.println("Unknown host: " + serverHostname);
				System.exit(1);
			} catch (IOException e) {
				System.err.println("Unable to get streams from server");
				System.exit(1);
			}

			/** {@link UnknownHost} object used to read from console */
			BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

			while (true) {
				System.out.print("client: ");
				String userInput = stdIn.readLine();
				/** Exit on 'q' char sent */
				if ("q".equals(userInput)) {
					break;
				}
				out.println(userInput);
				System.out.println("server: " + in.readLine());
			}

			/** Closing all the resources */
			out.close();
			in.close();
			stdIn.close();
			echoSocket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

Here is the output for both server and client.

Server

SocketServer Example
New client connected from 127.0.0.1
Message received:important message

Client

Connecting to host 127.0.0.1 on port 8081.
client: important message
server: important message
client: q

 

References