英文:
Is it Necessary to Check "n" returned by Write In Golang
问题
我有一个服务器,并启动一个goroutine来发送数据。代码如下:
func handleSend(conn *net.TcpConn, ch <-chan []byte) {
for {
select {
case msg, ok := <-ch:
if !ok {
return
}
n, err := conn.Write(msg)
if err != nil {
log.Error("conn write error", err)
return
}
// 在这里
}
}
}
今天,我认为我应该检查conn.Write
返回的n
,以确保msg
完全写入。所以我在here
的位置添加了以下代码:
for ; n != len(msg); {
log.Error("conn write not completely", len(msg), "actually", n)
msg = msg[n:]
n, err = conn.Write(msg)
if err != nil {
log.Error("conn write error", err)
return
}
}
我想知道这样做是否正确?
另外,如果对等方接收消息很慢,Write
只返回部分成功发送的数据会怎么样?
英文:
I have a server and start a goroutine for sending data. Code like this
func handleSend(conn *net.TcpConn, ch <-chan []byte) {
for {
select {
case msg, ok := <-ch:
if !ok {
return
}
n, err := conn.Write(msg)
if err != nil {
log.Error("conn write error", err)
return
}
//here
}
}
}
Today, I think I should check n
return by conn.Write
to make sure that msg
is writed completely. So I add the following code in the place here
for ;n!= len(msg);{
log.Error("conn write not completely", len(msg), "actually", n)
msg = msg[n:]
n, err = sess.conn.Write(msg)
if err != nil {
log.Error("conn write error", err)
return
}
}
And I want to know is it right to do this?
PS what if the peer receive message slowly and Write
return with only part of the data sended successfully ?
答案1
得分: 8
文档中说,如果Write
方法返回n < len(p)
,则必须返回一个非空的错误。你可能会发现对于n
你无法做太多处理,这种情况下你可以将其赋值给_
。
英文:
Docs say Write
must return a non-nil error if it returns n < len(p)
. You may well find there's not much you can do with n
, in which case you can assign it to _
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论