将任意数量的字节读取到缓冲区Golang中 [英] Read arbitrary amount of bytes into buffer Golang

查看:67
本文介绍了将任意数量的字节读取到缓冲区Golang中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从连接中读取信息流.我尚未编写服务器的一部分,也无权修改协议(否则我会让协议更友好)

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)

我试图在Go中编写一个服务,该服务将任意数量的字节读入循环中的缓冲区中,并将其传递给另一个处理程序(我也无法修改此部分)

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)

这是我当前的设置

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字节缓冲区?

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?

推荐答案

如果您想阅读整个连接流,可以使用:

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())

这篇关于将任意数量的字节读取到缓冲区Golang中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆