dqwd71332
2019-06-21 05:41 阅读 82
已采纳

指示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 doushen1026 2019-06-21 06:34

    Call shutdownOputput to match the code in the Go client.

    点赞 评论 复制链接分享

相关推荐