1 回答
TA贡献1966条经验 获得超4个赞
Reader的文档说:
Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n
<= len(p)) and any error encountered. Even if Read returns n < len(p), it may use
all of p as scratch space during the call. If some data is available but not
len(p) bytes, Read conventionally returns what is available instead of waiting
for more.
因此,问题的最可能原因是 Read 正在返回可用的数据(在本例中为单个字符)。您可以通过使用ioutil.ReadAll或在循环中执行读取来解决此问题(数据被添加到缓冲区的事实使它看起来像是最初的意图),例如:
for {
n, err := c.Read(tmp)
if err != nil {
if err != io.EOF {
// Note that data might have also been received - you should process that
// if appropriate.
log.Fatalf("connection Read() %v", err)
return
}
break // All data received so process it
}
buf = append(buf, tmp[:n]...)
}
注意:不保证收到任何数据;您应该在尝试访问它之前检查长度(即buf[0]可能会恐慌)
- 1 回答
- 0 关注
- 109 浏览
添加回答
举报