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 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn