Socket Programming in java

Socket Programming is used to provide the mechanism to connect two computers using TCP protocol .

  Socket Programming is used to implement reliable, bidirectional , persistent ,point to point ,stream based connection between two computer on internet.

  In Socket Programming , a Client program and a Server program establish a connection to one another. Each Program binds a socket to its end point of the connection.

  To communicate , the client and the server each reads from and writes to the socket bound to the connection.

  In Java , there are two classes to implement socket programming . These classes are Socket and ServerSocket .


Socket Class

Socket is class present in java.net package which represents TCP client . In order to create client we have to make object of Socket class in java.

Following constructor can be used to create object of Socket class to provide the functionality of TCP/IP client.

  public Socket(InetAddress local , int portNumber )throws IOException : it used to create a socket (client) using Inet Address object and a port.

  public Socket(String hostName , int portNumber )throws UnknownHostException, IOException : it used to create a socket (client) using hostName and a port.

Commonly used method of the Socket class.

Important methods

Method Description
public InputStream getInputStream() returns the InputStream attached with this socket.
public OutputStream getOutputStream() returns the OutputStream attached with this socket.
public void close() closes this socket
public int getPort() return the invoking port to which the invoking Socket object is connected.
public InetAddress getInetAddress() return the InetAddress associated with the Socket Object.

We can gain access to the input and output streams associated with a Socket by the use of the getInputStream() and getOutputStream() methods.

ServerSocket class

This class represents the functionality of TCP/IP server in java. Object of ServerSocket is used to establish communication with the clients.

Following constructor of ServerSocket class can be used to create TCP/IP server object .

  public ServerSocket(int portNumber)throws IOException : it creates server socket on the specified port with a queue length of 50.

  public ServerSocket(int portNumber , int maxQueueLength)throws IOException : it creates server socket on the specified port with a queue length of maxQueueLength.

Commonly used methods of ServerSocket Class

Important methods

  public Socket accept() - This method instruct TCP/IP server to establish network connection.
This method block the TCP/IP server until any incoming connection request is received , whenever a connection request is received it creates a connection and return the Socket Object.

  public void close() : This method is used to close the connection from the server.

UseCase :

Let there be a Host name with 'B' which is configured on port number 2000 as a TCP/IP server.
Host 'A' wants to communicate with Host 'B' as a TCP/Client using same port .

Program to make TCP Server using ServerSocket .
MyServer.java


import java.io.*;
import java.net.*;
class Myserver{
	public static void main(String[] args)throws Exception {
		//create the object of ServerSocket and bind it on port 2000
		ServerSocket server=new ServerSocket(2000);

		System.out.println("Server is ready ,Waiting for connection.....");

		Socket socket =server.accept();

		InputStream is=socket.getInputStream();

		BufferedReader br=new BufferedReader(new InputStreamReader(is));

		String str=br.readLine();
		System.out.println(str);

		//getting OutputStream to write data over network
		OutputStream os=socket.getOutputStream();
		PrintStream ps=new PrintStream(os);
		ps.println("Hello client you are connected to me.");

		server.close();//close the server socket
	}
}

Program to make Client using Socket .
MyClient.java


import java.io.*;
import java.net.*;
class MyClient{
	public static void main(String[] args)throws Exception {
		//create the socket connected to localhost ,port 2000
		Socket socket=new Socket("localhost",2000);

		//obtain input and output stream

		InputStream is=socket.getInputStream();//for reading data 
		OutputStream os=socket.getOutputStream();//for writing the data

		//create a massege to send to server
		String str="Hello server , I want to connect to you.";
		PrintStream ps=new PrintStream(os);
		ps.println(str);

		//read and display the response
		 BufferedReader br=new BufferedReader(new InputStreamReader(is));
		 String s=br.readLine();
		 System.out.println(s);

		 //close the socket
		 socket.close();

	}
}

Compile and Execute MyServer first then MyClient.

Output of above program

Example of Socket Programming.

Sending and Receiving the message to and from both side.

Program to create Server and configure the server on port : 5000.
MyServer.java


//this  is Myserver using java.net.ServerSocket
import java.net.*;
import java.io.*;

class MyServer {
	public static void main(String[] args) {
		try {
			ServerSocket server = new ServerSocket(5000);

			System.out
					.println("Server started....waiting for client (socket) connet.....");
			Socket s = server.accept();
            //get the InputStream
			InputStream is = s.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));

			while (true) {
				String msg = br.readLine();
				if (msg.equalsIgnoreCase("exit")) {
					break;
				}
				System.out.println(msg);

				// read the string from console using BufferedReader
				BufferedReader br1 = new BufferedReader(new InputStreamReader(
						System.in));
				String x = br1.readLine();

				// write the string to socket using PrintStream
				PrintStream ps = new PrintStream(s.getOutputStream());
				ps.println(x);
			}
			System.out.println("conversation ended successfully");
			server.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Program to create Client using Socket .
MyClient.java


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

class MyClient {
	public static void main(String[] args) {
		try {

			Socket s = new Socket("127.0.0.1", 5000);
			System.out
					.println("Write msg alternately ...Press \' exit \' to end conversation");
			while (true) {
				// read the string from console using buffered Reader
				BufferedReader br1 = new BufferedReader(new InputStreamReader(
						System.in));
				String x = br1.readLine();

				//print the string x to socket using PrintStream
				PrintStream ps = new PrintStream(s.getOutputStream());
				ps.println(x);
				if (x.equalsIgnoreCase("exit")) {
					break;
				}

				// get reader to read the string from server
				BufferedReader br = new BufferedReader(new InputStreamReader(
						s.getInputStream()));
				String msg = br.readLine();
				System.out.println(msg);

			}
			System.out.println("conversation ended successfully");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Compile and Run MyServer First and then MyClient.

Output of above program