Communication Between Server And Client Programs Using TCP/IP Protocol Using Socket In Java

LEVEL: Intermediate

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click  View Source “View Source” on the right of this code snippet.

Background and Explanation of the code


There are two programs. One is Server-side and another is Client-side. Both programs communicate with each other using TCP/IP protocol and Socket & ServerSocket classes of Java networking API.

1) TCPServer.java : This is Server-side program. It creates ServerSocket on specified port number and calls accept( ) method of it. The accept( ) method waits till any Client-side Socket get connected to it. Whenever any Client-side Socket is accepted by accept( ) method, it returns reference of that Client’s socket.

Two streams need to be created. PrintStream sends data to the Client’s socket. DataInputStream reads data from Client’s socket.

The Server-side program needs to be run first because as soon as Client’s socket is created in Client-side program it searches for ServerSocket in network.

2) TCPClient.java : This is Client-side program. It creates Socket with specific IP address and Server’s port number. As soon as this Client’s Socket is  created it searches for ServerSocket in network.

Two streams need to be created. PrintStream sends data to the Server’s socket. DataInputStream reads data from Server’s socket.

While running Client-side program Server’s IP Address/host-name needs to be passed from command-line argument.

First of all Client sends message to Server and then Server sends message to Client. Both programs can communicate and sends & receives messages one by one. Send message as ‘exit’ to stop the communication.

To run Server-side program: java TCPServer

To run Client-side program: java TCPClient <IPAddress>