dqwd71332 2019-06-21 05:41
浏览 94
已采纳

指示Go TCP Server Java TCP Client已完成写入流

I'm writing a Java TCP Client that connects to a Golang TCP Server.

The server uses the below code to read messages from clients:

func (tcpHandler TCPHandler) getClientMsgBytes(connection *net.TCPConn) ([]byte, error) {
    clientMsgBytes, err := ioutil.ReadAll(connection)
    if err != nil {            
        return nil, err
    }       

    return clientMsgBytes, nil
}

My client uses the below code to send messages to the server:

try (Socket socket = new Socket("localhost", 9000)) {
    byte[] message = getMessage();

    DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());

    outputStream.write(commandMessage);     

    // Read message from the sever...          
}

My problem is that the server keeps waiting for the client to write its message even after all bytes of the message have been written to the stream. This seems to be because the ioutil.ReadAll function is waiting for an io.EOF error as the signal to stop reading from the stream.

How can I tell Go that I am done writing to the TCP stream from Java? I can change both the Java TCP Client and Golang TCP Server codes, if that helps.

NOTE: The server was written like that because our Go TCP Client uses the below code:

func writeToConnection(connection *net.TCPConn, tcpCommand structs.TCPCommand) error {
    messageBytes, err := json.Marshal(tcpCommand)
    if err != nil {
        err = merry.Wrap(err)
        return err
    }

    _, err = connection.Write(messageBytes)
    if err != nil {
        err = merry.Wrap(err)
        return err
    }

    err = connection.CloseWrite()
    if err != nil {
        err = merry.Wrap(err)
        return err
    }

    return nil
}
  • 写回答

1条回答 默认 最新

  • doushen1026 2019-06-21 06:34
    关注

    Call shutdownOputput to match the code in the Go client.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?