如何改进此 tcp 套接字通信?

How to improve this tcp socket communication?

我正在尝试通过发送和接收消息的循环实现 TCP 套接字通信的微基准测试。但是,与某些图表中 TCP 套接字的标准延迟相比,我的延迟很高。 我怎样才能改进我的代码?

服务器端

    DataOutputStream output = new DataOutputStream(this.clientSocket.getOutputStream());
    DataInputStream input = new DataInputStream(this.clientSocket.getInputStream());
    int j = 0; 
    while (j < loop) {
        output.write(bytes);   
        input.read(new byte[input.readInt()] );             
        j++;
    }

客户端

    DataOutputStream output = new DataOutputStream(socket.getOutputStream());
    DataInputStream input = new DataInputStream(socket.getInputStream());
    final long startTime = System.nanoTime();
    int j = 0;
    while (j < loop) {   
         input.read(new byte[input.readInt()]);
         output.write(bytes);
    j++;    
    }

    final long endTime = System.nanoTime();
    final double difference = (endTime - startTime) / 1e6;
    LOGGER.info("Latency:"+ difference/loop);

您的代码甚至都不正确,因此到目前为止的结果毫无意义。您的发件人很可能因为应用程序协议未正确实施而卡住。

  • 你实际上没有写一个int,但双方:

    1. 阅读一篇int
    2. 假设它是后续消息的长度字,然后他们
    3. 可能无法完全阅读,因为他们忽略了 read() 的结果。

    同一事物的正确版本必须从某人开始,显然是服务器,写下初始的int

  • 您还使用了无缓冲 I/O,这在 readInt()writeInt() 情况下相当昂贵。

  • 你还在不必要地在两端制造大量垃圾。

服务器:

DataOutputStream output = new DataOutputStream(ne w BufferedOutputStream(this.clientSocket.getOutputStream()));
DataInputStream input = new DataInputStream(new ByufferedInputStream(this.clientSocket.getInputStream()));
byte[] message - new byte[8192]; // or whatever
int msgLen = message.length;
while (j < loop)
{
    output.writeInt(msgLen);
    output.write(message);
    output.flush();
    int replyLen = input.readInt();
    input.readFully(message, 0, replyLen); // assuming replyLen <= msgLen
    j++;
}

客户端(以相同的方式构造数据流并使用相同的 messagemsgLen 变量后:

while (j < loop) {
    mgLen = input.readInt();
    input.readFully(message, 0, msgLen); // same assumption as above
    output.writeInt(msgLen);
    output.write(message, 0, msgLen);
    output.flush();
    j++;    
}

E&OE