【问题标题】:How to improve this tcp socket communication?如何改进这个 tcp socket 通信?
【发布时间】:2017-11-09 10:34:36
【问题描述】:

我正在尝试通过发送和接收消息的循环来实现 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);

【问题讨论】:

  • 请记住,System.nanoTime() 和 System.currentTimeMillis() 的准确性取决于系统,对于您的用例可能不够准确。
  • 标准延迟?延迟将取决于网络拥塞,这是您在 Internet 上无法控制的。另外,您不应该使用 readFully 方法吗? read() 可以并且将返回比请求更少的字节。 bytes 是什么?你如何定义延迟?

标签: java sockets latency microbenchmark


【解决方案1】:

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

  • 你实际上没有写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++;
}

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

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

电子与工程

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 2014-11-05
    • 2020-07-06
    • 2012-03-08
    • 2018-01-31
    • 2011-05-30
    • 1970-01-01
    相关资源
    最近更新 更多