Question

Under here you find a simple server/client app that sends the integer 5 from the client to the server, which reads it and sends it back to the client. On the server I have placed a latency meter around the DataInputStream.readInt() method, which reads that this method is causing a 400 ms latency.

Server code:

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

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

// declaration section:
        ServerSocket echoServer = null;
        Socket clientSocket = null;
        int x;

// Try to open a server socket on port 4444
        try {
           echoServer = new ServerSocket(4444);
        }
        catch (IOException e) {
           System.out.println(e);
        }

//accept connection
        try {
           clientSocket = echoServer.accept();
//input
           DataInputStream input = new DataInputStream(clientSocket.getInputStream());
//output
           DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
//loop
           while(true){
               long time = System.currentTimeMillis();
               output.writeInt(input.readInt());
               long dtime = System.currentTimeMillis();
               System.out.println(dtime-time);
           }
//close
//           output.close();
//           input.close();
//           clientSocket.close();
//           echoServer.close();
        }catch (IOException e) {
           System.out.println(e);
        }
    }
}

Client code:

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

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

// declaration section:
// clientClient: our client socket
// out: output stream
// in: input stream

        Socket clientSocket = null;
// Initialization section:
// Try to open a socket on port 4444
// Try to open input and output streams
        try{
            clientSocket = new Socket("YOUR-IP-HERE", 4444);

//output
            DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
//input
            DataInputStream input = new DataInputStream(clientSocket.getInputStream());
//loop
        while(true) {
            output.writeInt(5);
            //System.out.println(input.readInt());
        }
//close
//            output.close();
//            input.close();
//            clientSocket.close();
        }catch(Exception e) {
            System.out.println("error");
        }
    }
}

Problem area:

//latencymeter
long time = System.currentTimeMillis();
//problem code
output.writeInt(input.readInt());
//latencymeter
long dtime = System.currentTimeMillis();
System.out.println(dtime-time);

Am I making a mistake in my code or am I not coding efficiently, please let me know.

Thanks

Was it helpful?

Solution

Solved: Adding clientSocket.setTcpNoDelay(true); on both server and client has brought the latency down to a normal 10-20 ms.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top