Java Socket Programming (Client Server Program)

In this tutorial I have shared simple client server program example to explain java socket programming.

In this example I will use Socket and ServerSocket classes for connection oriented socket programming. Since data is shared between server and client over network in the form of streams so DataInputStream and DataOutputStream classes are used.

Java Socket Programming (Client Server Program)

Server

import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

class server {
	public static void main(String args[]){
		try{
			//create socket, 5000 is port number
			ServerSocket serverSocket = new ServerSocket(5000);  

			System.out.println("Waiting for Client...");

			//establish connection
			Socket socket = serverSocket.accept();

			System.out.println("Client Connected...");

			//fetch incoming message
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			String  message = (String)dis.readUTF();
			
			System.out.println("Client message: " + message);  
			
			//close connection
			serverSocket.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

Above code is used to create server which is running on localhost on port number 5000.

Client

import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;

class client {
	public static void main(String args[]){
		String message;
		
		Scanner sc = new Scanner(System.in);
		
		try{
			//localhost because server is running on local machine, otherwise use ip of server
			Socket socket = new Socket("localhost", 5000);

			System.out.println("Connected with Server...");
			
			System.out.println("enter a message: ");
			message = sc.nextLine();

			//sending the message
			DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
			dout.writeUTF(message);  
			dout.flush();
			dout.close();
			
			//close connection
			socket.close();  
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

Since the server is running on local machine so I have used locahost while creating connection. Otherwise use the IP address of server.

How to Execute?

1. First open a command prompt and run server program. The server will wait for client to be connected.

2. Now open another command prompt and run client program. This will connect client with server. Enter a message at client side to send it to server.

See below screenshot as an example.

Java Socket Programming (Client Server Program)

Comment below if you have any queries regarding above client server program in java.

Leave a Comment

Your email address will not be published. Required fields are marked *