donglin9068
2015-08-22 08:18
浏览 181
已采纳

如何在客户端通过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?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题