OK so this post is going to be on Socket Programming in Java. A socket is one endpoint of a two-way communication link between two programs running on the network.
A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.
A socket looks something like this 128.1.21.11:3866.
Here 3866 helps the TCP layer identify the application that data is destined to be sent.
Socket Programming is generally used for developing Client Server applications. The Server program is always waiting to listen for a client request.
So firstly, we create the server program and run it. We will be using two classes, Socket and ServerSocket. Both these classes can be found in the package java.net.*;.
ServerSocket object binds the program to a certain port and Socket object is used to interact with the client.
Server Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.io.*; import java.net.*; public class DemoServer { public static void main(String[] args) { ServerSocket ss; Socket s; try { ss = new ServerSocket(1234); s = ss.accept(); System.out.println("Connected to "+s.getLocalAddress()); } catch (IOException e) { e.printStackTrace(); } } } |
Client Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.io.*; import java.net.*; public class DemoClient { public static void main(String args[]){ Socket s; try { s = new Socket("localhost", 1234); System.out.println("Connection established."); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
Server Program Output:

Client Program Output:
