dsfdsf23423
dsfdsf23423
2014-07-03 16:04
浏览 413
已采纳

在golang中使用net.TCPConn时,如何在不预先指定字节片长度的情况下进行读取?

I was trying to read some messages from a tcp connection with a redis client (a terminal just running redis-cli). However, the Read command for the net package requires me to give in a slice as an argument. Whenever I give a slice with no length, the connection crashes and the go program halts. I am not sure what length my byte messages need going to be before hand. So unless I specify some slice that is ridiculously large, this connection will always close, though this seems wasteful. I was wondering, is it possible to keep a connection without having to know the length of the message before hand? I would love a solution to my specific problem, but I feel that this question is more general. Why do I need to know the length before hand? Can't the library just give me a slice of the correct size?

Or what other solution do people suggest?

图片转代码服务由CSDN问答提供 功能建议

我正尝试从与Redis客户端(仅运行redis-cli的终端)的tcp连接中读取一些消息 。 但是,对于net软件包的 Read 命令要求我将切片作为 论点。 每当我提供没有长度的切片时,连接就会崩溃,并且go程序会暂停。 我不确定我的字节消息需要多长。 因此,除非我指定一些非常大的切片,否则此连接将始终关闭,尽管这似乎很浪费。 我想知道,是否可以保持连接而不必事先知道消息的长度? 我希望可以解决我的特定问题,但是我觉得这个问题更笼统。 为什么我需要事先知道长度? 图书馆不能只给我一个正确大小的切片吗?

还是人们建议其他解决方案?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongwu8050
    dongwu8050 2014-07-03 16:45
    已采纳

    Not knowing the message size is precisely the reason you must specify the Read size (this goes for any networking library, not just Go). TCP is a stream protocol. As far as the TCP protocol is concerned, the message continues until the connection is closed.

    If you know you're going to read until EOF, use ioutil.ReadAll

    Calling Read isn't guaranteed to get you everything you're expecting. It may return less, it may return more, depending on how much data you've received. Libraries that do IO typically read and write though a "buffer"; you would have your "read buffer", which is a pre-allocated slice of bytes (up to 32k is common), and you re-use that slice each time you want to read from the network. This is why IO functions return number of bytes, so you know how much of the buffer was filled by the last operation. If the buffer was filled, or you're still expecting more data, you just call Read again.

    点赞 评论

相关推荐