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

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

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

问题

我有一个服务器,并启动一个goroutine来发送数据。代码如下:

  1. func handleSend(conn *net.TcpConn, ch <-chan []byte) {
  2. for {
  3. select {
  4. case msg, ok := <-ch:
  5. if !ok {
  6. return
  7. }
  8. n, err := conn.Write(msg)
  9. if err != nil {
  10. log.Error("conn write error", err)
  11. return
  12. }
  13. // 在这里
  14. }
  15. }
  16. }

今天,我认为我应该检查conn.Write返回的n,以确保msg完全写入。所以我在here的位置添加了以下代码:

  1. for ; n != len(msg); {
  2. log.Error("conn write not completely", len(msg), "actually", n)
  3. msg = msg[n:]
  4. n, err = conn.Write(msg)
  5. if err != nil {
  6. log.Error("conn write error", err)
  7. return
  8. }
  9. }

我想知道这样做是否正确?
另外,如果对等方接收消息很慢,Write只返回部分成功发送的数据会怎么样?

英文:

I have a server and start a goroutine for sending data. Code like this

  1. func handleSend(conn *net.TcpConn, ch &lt;-chan []byte) {
  2. for {
  3. select {
  4. case msg, ok := &lt;-ch:
  5. if !ok {
  6. return
  7. }
  8. n, err := conn.Write(msg)
  9. if err != nil {
  10. log.Error(&quot;conn write error&quot;, err)
  11. return
  12. }
  13. //here
  14. }
  15. }
  16. }

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

  1. for ;n!= len(msg);{
  2. log.Error(&quot;conn write not completely&quot;, len(msg), &quot;actually&quot;, n)
  3. msg = msg[n:]
  4. n, err = sess.conn.Write(msg)
  5. if err != nil {
  6. log.Error(&quot;conn write error&quot;, err)
  7. return
  8. }
  9. }

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:

确定