如何在客户端通过TCP连接发送的一条消息中读取所有数据而不会在Go中阻塞?

如何在客户端通过TCP连接发送的一条消息中读取所有数据而不会在Go中阻塞?

问题描述:

I am implementing the server of a procotol in Go. In this protocol, the client connects to server and can send a bunch of commands, and expects a response from server after each command is sent. The command message is of this format:COMMAND <BODY_LENGTH> BODY , where the BODY_LENGTH is arbiturary, and specified on the command line.

The way I am parsing the command is: Read the first few bytes from net.Conn, parse the command and body length, and read the entire body with another read, process the message, send a response, and loops to wait for the next command message on the connection:

func handler(c net.Conn) {
    defer c.Close()
    for {
        msg := make([]byte, 1024)

        n, err := c.Read(msg)
        cmd, bodyLength = parseCommand(msg)
        // read the body of body length here
        if err == io.EOF {
            fmt.Printf("Client has closed the connection")
            break
        } 

        response := handleCommand(cmd, body)
        n, err := c.Write(response)
        if err != nil {
            fmt.Printf("ERROR: write
")
            fmt.Print(err)
        }
        fmt.Printf("SERVER: sent %v bytes
", n)
    }
}

I assume (Go documentation isn't clear on this) net.Conn.Read() to block when waiting for the next message from client and only return io.EOF when the client has close the connection. Correct me if I am wrong.

If the command is well-formatted, everything is fine. But if the command is ill-formatted, and I don't get a body length in the first line, I wish I can still read the rest of message, discard it, and wait for the next possibly valid message. The problem is, if I don't know the length of data to expect, I may start a read() that blocks if I have just read the last byte.

How can I read the entire message (everything buffered) without knowing its length? Or do I have to close the connection, and tell client to start a new connection for the next command?

  • There is no such thing as a message in TCP.
  • There is no guarantee that all the bytes sent by a single send() will arrive together, or that they will all fit into the receiver's socket receive buffer.
  • It is therefore impossible to accomplish your objective.

It is also pointless. You can't do anything until the entire command arrives, and you are certainly goino to be blocking between commands anyway. Blocking during reception of a command doesn't do any further harm.