TCP/IP Socket Programming in Java

Prayukti Jain
The Startup
Published in
6 min readJul 23, 2020

--

TCP is a Network Protocol that stands for Transfer Control Protocol, which allows well-founded communication between applications. TCP is consistently used over the Internet Protocol, and that is why referred to as TCP/IP. The communication mechanism between two systems, using TCP, can be established using Sockets and is known as Socket Programming. Hence, socket programming is a concept of Network Programming, that suggests writing programs that are executed across multiple systems, which are connected to each other using a network.

The mechanism for Socket Programming

A client creates a socket at its end of transmission and strives to connect the socket to the server. When a connection is established, the server creates a socket at its end and, the client and server can now ready communicate through writing and reading methods. Following is the elaborated procedure of what happens when a TCP connection is established:

  1. An object of ServerSocket is instantiated, and desired port number is specified, on which connection is going to take place.
  2. The accept method of ServerSocket is invoked, in order to hold the server in listening mode. This method won’t resume until a client is connected to the server through the given port number.
  3. Now, on the client-side, an object of Socket is instantiated, and desired port number and IP address is specified for the connection.
  4. An attempt is made, for connecting the client to the server using the specified IP address and port number. If the attempt is successful, the client is provided with a Socket that is capable of communicating to the respective server, with write and read methods. If unsuccessful, the desired exception is raised.
  5. Since a client is connected to the server, accept method on the server-side resumes, providing a Socket that is capable of communicating to the connected client.
  6. Once the communication is completed, terminate the sockets on both, the server and the client-side.

Now, communication is held using input/output streams of Sockets. The InputStream of the client is coupled with the OutputStream of the server and the OutputStream of the client is coupled with the InputStream of the server. Since TCP is a two-way network protocol, hence information can flow through both the streams at the time.

Client-Side Programming

For the Client machine, we need to now establish the socket connection. Socket Connection is when the two machines have information about each other’s network location (IP Address) and the TCP port.

Connection:

Socket socket = new Socket(IP Address, port number);
//IP Address of the server
//TCP port Number on which the server is listening

Communication:

The communication is held using the output and input streams. These streams are responsible for transmitting the information in the form of byte array. An object can also be transmitted through these streams, but it needs to be serialized before transmitting and deserialized after it has been received. Input and output streams are made available through socket instances.

Terminating Connection:

The socket connection needs to be terminated explicitly once the communication is fulfilled.

Implementation:

Below is the client-side implementation of socket programming in java.

import java.io.*;
import java.net.*;
class Client
{
public static void main(String data[])
{
//data is taken as command line argument
String ipAddress=data[0];
int portNumber=Integer.parseInt(data[1]);
int rollNumber=Integer.parseInt(data[2]);
String name=data[3];
String gender=data[4];
String request=rollNumber+”,”+name+”,”+gender+”#”;
//”#” acts as a terminator
try
{
Socket socket=new Socket(ipAddress , portNumber);
// Socket is initialized and attempt is made for connecting to the server
// Declaring other properties and streams
OutputStream outputStream;
OutputStreamWriter outputStreamWriter;
InputStream inputStream;
InputStreamReader inputStreamReader;
StringBuffer stringBuffer;
String response;
int x;
// retrieving output Stream and its writer, for sending request or acknowledgement
outputStream=socket.getOutputStream();
outputStreamWriter=new OutputStreamWriter(outputStream);
outputStreamWriter.write(request);
outputStreamWriter.flush(); // request is sent
// retrieving input stream and its reader, for receiving acknowledgement or response
inputStream=socket.getInputStream();
inputStreamReader=new InputStreamReader(inputStream);
stringBuffer=new StringBuffer();
while(true)
{
x=inputStreamReader.read();
if(x==’#’ || x==-1) break; // reads till the terminator
stringBuffer.append((char)x);
}
response=stringBuffer.toString();
System.out.println(response);
socket.close(); //closing the connection
}catch(Exception exception)
{
// Raised in case, connection is refused or some other technical issue
System.out.println(exception);
}
}
}

Server-Side Programming

For the server-side programming, a ServerSocket is required, which will wait for the client in the listening mode, on a particular TCP port. This ServerSocket holds until a Client Socket is connected successfully. As soon as the client is connected, another Socket comes into existence that will enable data sharing between the respective client and server. A temporary Socket is created to handle the request from that particular client and our main server socket will be free again, to listen to other requests. Hence we have ServerSocket and Socket on the server-side.

Creating ServerSocket:

The ServerSocket is instantiated on a specific port number. Then, the server starts listening for the client requests coming in for that port number. The accept method waits until a client connects to the server. After a successful connection, accept returns a Socket that will facilitate the communication.

Communication:

For data transfer, the getOutputStream method is used to send the output through the socket, and input is received using getInputStream method. The Server keeps receiving messages until it receives the terminator.

Terminating Connection:

Once the response is sent, the socket, along with the input and output streams needs to be closed explicitly.

Implementation:

The Server implemented below is a multi-threaded server, so it can listen to multiple clients without any interruption. This works efficiently because, after establishing the connection, the server diverts the request, along with the respective socket, to another Thread or another Request Processor. The request processor will continue to work by using the socket, it received. Meanwhile, Server can listen to other requests coming in. As the connection is closed, the thread is also terminated.

import java.io.*;
import java.net.*;
class RequestProcessor extends Thread //for multi-threaded server
{
private Socket socket;
RequestProcessor(Socket socket)
{
this.socket=socket;
start(); // will load the run method
}
public void run()
{
try
{
//Declaring properties and streams
OutputStream outputStream;
OutputStreamWriter outputStreamWriter;
InputStream inputStream;
InputStreamReader inputStreamReader;
StringBuffer stringBuffer;
String response;
String request;
int x;
int temp1,temp2;
String part1,part2,part3;
int rollNumber;
String name;
String gender;
//getting input stream and its reader, for reading request or acknowledgement
inputStream=socket.getInputStream();
inputStreamReader=new InputStreamReader(inputStream);
stringBuffer=new StringBuffer();
while(true)
{
x=inputStreamReader.read();
if(x=='#' || x==-1) break; //reads until terminator
stringBuffer.append((char)x);
}
request=stringBuffer.toString();
System.out.println("Request : "+request);
//parsing and extracting Request data
temp1=request.indexOf(",");
temp2=request.indexOf(",",temp1+1);
part1=request.substring(0,temp1);
part2=request.substring(temp1+1,temp2);
part3=request.substring(temp2+1);
rollNumber=Integer.parseInt(part1);
name=part2;
gender=part3;
System.out.println("Roll number : "+rollNumber);
System.out.println("Name : "+name);
System.out.println("Gender : "+gender);

// handle data
//sending response
response="Data saved#";
//get output stream and its writer, for sending response or acknowledgement
outputStream=socket.getOutputStream();
outputStreamWriter=new OutputStreamWriter(outputStream);
outputStreamWriter.write(response);
outputStreamWriter.flush(); // response sent
System.out.println("Response sent");
socket.close(); //terminating connection
}catch(Exception exception)
{
System.out.println(exception);
}
}
}
class Server
{
private ServerSocket serverSocket;
private int portNumber;
Server(int portNumber)
{
this.portNumber=portNumber;
try
{
//Initiating ServerSocket with TCP port
serverSocket=new ServerSocket(this.portNumber);
startListening();
}catch(Exception e)
{
System.out.println(e);
System.exit(0);
}
}
private void startListening()
{
try
{
Socket socket;
while(true)
{
System.out.println("Server is listening on port : "+this.portNumber);
socket=serverSocket.accept(); // server is in listening mode
System.out.println("Request arrived..");
// diverting the request to processor with the socket reference
new RequestProcessor(socket);
}
}catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String data[])
{
int portNumber=Integer.parseInt(data[0]);
Server server=new Server(portNumber);
}
}

Execution

To run, compile the server and client code. First, start the server in a prompt like this:

Compile and execute the client in another prompt like this:

After the data is sent from the client, the server prompt will look like this:

Multiple printing of Server is listening on port: 5050 is the proof of concept that, once the request has arrived, the server diverts it onto another thread and gets ready for listening to another request. And extracting and processing the data takes place on another thread in parallel.

Conclusion

In this article, we understood the basic concept of Network Programming and TCP/IP socket programming, the procedure and implementation of the Client and Server side Services, using a multi-threaded server.

Do look out for other articles to get the knowledge about various topics and feel free to drop a comment for doubts or suggestions.

What are the top 10 useful functions of Underscore.js?

What are Decorators in Python?

Multithreading in Java

Understanding Apache Derby using Java

TCP/IP Socket Programming in Java

How to send HTTP Requests using React JSX?

--

--

Prayukti Jain
The Startup

Software Engineer at Walmart Global Tech | Content Writer | Open to Learn and Help