duandao7704 2016-03-04 01:16
浏览 98
已采纳

读取net.Conn缓冲区的第一个UVarInt

I have a TCP packet connection (net.Conn) set up by listening on a port.

conn, err := ln.Accept()

I need to read the first UVarInt of the Conn.Read([]byte) buffer, which starts at index 0.

Previously, I would only need the first byte, which is easy to do using

packetSize := make([]byte, 1)
conn.Read(packetSize)
// Do stuff with packetSize[0]

However, as previously mentioned, I need to get the first UVarInt I can reach using the net.Conn.Read() method. Keep in mind that a UVarInt can have pretty much any length, which I cannot be sure of (the client doesn't send the size of the UVarInt). I do know however that the UVarInt starts at the very beginning of the buffer.

  • 写回答

1条回答 默认 最新

  • douhanzhen8927 2016-03-04 01:20
    关注

    Wrap the connection with a bufio.Reader:

    br := bufio.NewReader(conn)
    

    Use the binary package to read an unsigned varint through the bufio.Reader:

    n, err := binary. ReadUvarInt(br)
    

    Because the bufio.Reader can buffer more than the varint, you should use the bufio.Reader for all subsequent reads on the connection.

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog