2

在这里,您会找到一个简单的服务器/客户端应用程序,它将整数 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);

我是在代码中犯了错误还是我没有有效地编码,请告诉我。

谢谢

4

1 回答 1

1

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

于 2011-10-28T18:57:26.203 回答