DataInputStream.readInt()导致高延迟,我这样做错了吗?

时间:2011-10-27 23:49:04

标签: networking network-programming latency datainputstream

在这里,您可以找到一个简单的服务器/客户端应用程序,它将整数5从客户端发送到服务器,服务器读取它并将其发送回客户端。在服务器上,我在DataInputStream.readInt()方法周围放置了一个延迟计,该方法读取此方法导致400毫秒的延迟。

服务器代码:

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);
        }
    }
}

客户代码:

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");
        }
    }
}

问题区域:

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

我在代码中犯了错误,或者我没有高效编码,请告诉我。

由于

1 个答案:

答案 0 :(得分:1)

解决:添加clientSocket.setTcpNoDelay(true);服务器和客户端都将延迟降低到正常的10-20毫秒。