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条回答 默认 最新

  • duanjiyun7391 2015-08-22 08:41
    关注
    • 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.

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

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。