英文:
Read arbitrary amount of bytes into buffer Golang
问题
我正在尝试从连接中读取一串信息。我还没有编写服务器部分,并且无法修改协议(否则我会使协议更友好)。
我正在尝试在Go中编写一个服务,它会循环将任意数量的字节读入缓冲区,并将其传递给另一个处理程序(我也无法修改此部分)。
这是我的当前设置:
buf := make([]byte, 256)
for {
n, err := conn.Read(buf)
fmt.Println(string(buf))
if err != nil || n == 0 {
return
}
Handle(buf[:n])
}
当有足够的字节可读时,这个方法运行良好... 但是,在流的末尾,可能没有256个可读字节。有没有办法在Read()方法正常返回时保留我的256字节缓冲区呢?
英文:
I'm trying to read a stream of info from a connection. I haven't written the server part of it, and don't have access to modifying the protocol (or else I would have made the protocol much friendlier)
I'm trying to write a service in Go that reads an arbitrary number of bytes into a buffer in a loop and passes it off to another handler (I also cannot modify this part)
This is my current setup
buf := make([]byte, 256)
for {
n, err := conn.Read(buf)
fmt.Println(string(buf))
if err != nil || n== 0 {
return
}
Handle(buf[:n])
}
This works fine when there are enough bytes to be read... However, at the end of the stream, there aren't 256 bytes that are readable. Is there any way to preserve my 256 byte buffer while Read() to gracefully return?
答案1
得分: 7
如果你想读取整个连接的数据流,你可以使用以下代码:
var b bytes.Buffer
if _, err := io.Copy(&b, conn); err != nil {
return err
}
Handle(b.Bytes())
这段代码会将连接的数据流复制到一个缓冲区中,并将缓冲区的内容传递给 Handle
函数进行处理。
英文:
If you want to read the whole stream of the connection you could use:
var b bytes.Buffer
if _, err:= io.Copy(&b, conn); err != nil {
return err
}
Handle(b.Bytes())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论