在这里你会发现一个简单的服务器/客户端应用程序,它将整数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);
我在我的代码中犯了一个错误,或者我没有有效地编码,请让我知道。
谢谢
已解决:添加clientSocket.setTcpNoDelay(true);在服务器和客户端都将延迟降低到正常的10-20毫秒。