Skip to main content

TCP Client and Server program in Java

TCP:
Transport control protocol is transport layer protocol in TCP/IP model. It is connection oriented and reliable protocol. It guarantees packet transmission between process to process.
Connection oriented means that for transmission before starting connection is established and then data is transmitted, that is the reason reliability comes into the picture.

So below is typical abstract diagram for TCP protocol, please note this picture just shows the overall functionality of the entire process not the specifics, for more information please click here.
TCP Handshaking Process

The TCP Server Code in java is given below:

This is a demo program which will take sort alphabets sent from client program.

import java.net.*;
import java.util.Arrays;
import java.io.*;


public class TCPServer{
    private  ServerSocket serverSocket;
    
    public TCPServer(int port) throws IOException
    {
       serverSocket = new ServerSocket(port); // setting port number @server
       serverSocket.setSoTimeout(10000); // timeout of socket @server
    }

    
    public static void main(String [] args) throws IOException
    {
       int port = 1025;
       TCPServer tcpServer = new TCPServer(port);
       while(true)
       {
          try
          {
             System.out.println("Waiting for client on port " +
             tcpServer.serverSocket.getLocalPort() + "...");
             
             Socket server = tcpServer.serverSocket.accept();  // Con is established
             
             System.out.println("Just connected to " + server.getRemoteSocketAddress());
             
             DataInputStream in =  new DataInputStream(server.getInputStream());
             
             String[] arr = in.readUTF().split(" ");   // getting data from client
             
             // Performing sorting operation
             String line="";
             Arrays.sort(arr);
             for(String a: arr) line += a+" " ;
             
             DataOutputStream out = new DataOutputStream(server.getOutputStream()); 
             
             out.writeUTF(line); // sending data to client
             server.close();             
             
          }catch(SocketTimeoutException s)
          {
             System.out.println("Socket timed out!");
             break;
          }catch(IOException e)
          {
             e.printStackTrace();
             break;
          }
       }
        
    }
}


The code is self descriptive.



The Code for TCP Client program:


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

public class TCPClient {
    public static void main(String argv[]) throws Exception
    {
     String serverName = "localhost";
     int port = 1025;
     try{
  
          System.out.println("Connecting to " + serverName +
       " on port " + port+" ..");   // Connection request
          
          // Connection reply
          Socket client = new Socket(serverName, port);                                   
         

          System.out.println("Just connected to "  
        + client.getRemoteSocketAddress());   // get local port from server
          
          // get output stream towards server
          OutputStream outToServer = client.getOutputStream();                           
          DataOutputStream out = new DataOutputStream(outToServer);
          
          System.out.println("sending : Z X C V B N M A to server :"+serverName); 
          out.writeUTF("Z X C V B N M A");      // sending data to server
          
          InputStream inFromServer = client.getInputStream();   
          DataInputStream in = new DataInputStream(inFromServer);
         System.out.println("Server replied: "
         +in.readUTF());    // getting reply from server
          
          client.close();
     }
     catch(IOException e){
  e.printStackTrace();
     }
    }
}





Note:  

  1. We have taken port 1025 as the port on which client will make the request. We have taken this port as ports from 0-1024 are reserved and we can not use them for our experiment purposes.
  2. You have seen "setSoTimeout", this will limit the time of server to wait for client.


How to Run the above code:

  1. First run the server code
  2. Then run the client code.



The Output:
Connecting to localhost on port 1025 ..
Just connected to localhost/127.0.0.1:1025
sending : Z X C V B N M A to server :localhost

Server replied: A B C M N V X Z 

Comments

Popular posts from this blog

Reliable User Datagram Protocol

RUDP provides  a solution where UDP  is too primitive because guaranteed-order  p acket  delivery is desirable, but  T CP  adds too much overhead.  In order for RUDP to gain higher Quality of Service , RUDP implements features that are similar to TCP with less overhead. Implementations: In order to ensure quality, it extends UDP by means of adding the following features: Acknowledgment of received packets Flow control Re-transmission of lost packets Over buffering (Faster than real-time streaming) RUDP is not currently a formal standard, however it was described in an n 1999. It has not been proposed for standardization. Working Example: One way to think about how RUDP types of transport work is to use a basic model where all the data is sent in UDP format, and each missing packet is indexed.  Once the main body of the transfer is done, the recipient sends the sender the index list and the sender re-transmits ...

Goodness of Fit Test for normal and poisson distribution

Meaning of Goodness of fit test: We find out which distribution fits the sample data the most. And this is achieved using chi-square distribution (Snedecor and Cochran, 1989). How to apply: There are 4 steps to follow: State the hypothesis:  Data follows a distribution or not Criteria to reject null hypothesis: if Χ 2  > Χ 2 (k,1-α) then reject null hypothesis. Analyze sample data: Compute the chi-square value using below formula: ∑(Oi- Ei) 2 /Ei        : Oi is observed frequency and Ei is expected frequency Interpret the results: Declare the results after comparing the values of Χ 2 and Χ 2 (k,1-α), where k is degree of freedom and  α is significance level. Degree of Freedom: It is  =  n - 1 - m m: number of parameter in the distribution. So in case of normal distribution m is 2 ( μ ,α) and in case of poisson dist. m is = 1 ( λ). Example 1: Goodness of fit test for Normal Distribution Year wise d...

Red Black Tree Deletion in Java

Red Black tree deletion involves following cases: If node to delete is a RED leaf node then just delete it. If node to delete is a BLACK node and has one red child then, just replace it with child and retain color of node to be deleted. If node is having more than two children then just replace the node with in-order predecessor and call the delete routine at in-order predecessor recursively. But the problem arises when node to delete is a BLACK node and it has only one BLACK child or node to be deleted is a BLACK leaf node. Then DOUBLE BLACK problem arises. Note: Points form 1 to 3 are easy to implement and can be understood using the code given below. To resolve DOUBLE BLACK problem we have following four cases: Why double black problem: Suppose we have deleted a BLACK node and the number of nodes in the path going through it is reduced by 1. So the BLACK replacement will carry one extra BLACK color to retain property 5 of RB Tree that in any path from root to leaf...