Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

networking

go

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 ?

like image 743
frank.lin Avatar asked Feb 12 '23 09:02

frank.lin


1 Answers

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 _.

like image 184
twotwotwo Avatar answered Feb 14 '23 00:02

twotwotwo