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

huangapple go评论89阅读模式
英文:

Reading the first UVarInt of a net.Conn buffer

问题

我有一个通过监听端口建立的TCP数据包连接(net.Conn)。

conn, err := ln.Accept()

我需要读取Conn.Read([]byte)缓冲区的第一个UVarInt,它从索引0开始。

以前,我只需要第一个字节,可以使用以下代码轻松实现:

packetSize := make([]byte, 1)
conn.Read(packetSize)
// 使用 packetSize[0] 进行处理

然而,正如之前提到的,我需要获取使用net.Conn.Read()方法能够读取到的第一个UVarInt。请记住,UVarInt的长度可以是任意的,我无法确定(客户端不会发送UVarInt的大小)。但我知道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

得分: 4

使用bufio.Reader对连接进行包装:

br := bufio.NewReader(conn)

使用binary包通过bufio.Reader来读取无符号varint

n, err := binary.ReadUvarInt(br)

由于bufio.Reader可以缓冲多个varint,因此您应该在连接上的所有后续读取操作中使用bufio.Reader。

英文:

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.

huangapple
  • 本文由 发表于 2016年3月4日 09:16:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/35786264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定