Is it Necessary to Check "n" returned by Write In Golang

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

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 &lt;-chan []byte) {
    for {
        select {
        case msg, ok := &lt;-ch:
            if !ok {
                return
            }
            n, err := conn.Write(msg)
            if err != nil {
                log.Error(&quot;conn write error&quot;, 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(&quot;conn write not completely&quot;, len(msg), &quot;actually&quot;, n)
     msg = msg[n:]
     n, err = sess.conn.Write(msg)
     if err != nil {
         log.Error(&quot;conn write error&quot;, 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 &lt; len(p),则必须返回一个非空的错误。你可能会发现对于n你无法做太多处理,这种情况下你可以将其赋值给_

英文:

Docs say Write must return a non-nil error if it returns n &lt; len(p). You may well find there's not much you can do with n, in which case you can assign it to _.

huangapple
  • 本文由 发表于 2014年12月9日 12:37:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/27371518.html
匿名

发表评论

匿名网友

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

确定