简体   繁体   English

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

[英]Indicate to Go TCP Server that Java TCP Client Has Finished Writing to the Stream

I'm writing a Java TCP Client that connects to a Golang TCP Server. 我正在编写连接到Golang TCP服务器的Java TCP客户端。

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. 这似乎是因为ioutil.ReadAll函数正在等待io.EOF错误,作为停止从流中读取的信号。

How can I tell Go that I am done writing to the TCP stream from Java? 如何告诉Go我已经完成了从Java写入TCP流的准备? I can change both the Java TCP Client and Golang TCP Server codes, if that helps. 如果有帮助,我可以更改Java TCP Client和Golang TCP Server代码。

NOTE: The server was written like that because our Go TCP Client uses the below code: 注意:服务器是这样写的,因为我们的Go TCP Client使用以下代码:

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
}

调用shutdownOputput以匹配Go客户端中的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM