简体   繁体   中英

golang TCPConn.Write method call

Sorry for my English.This English is not my native language.

I want to send data out via tcp,but I do not know should call Write method directly or call Write method in for loop.

So I want to know these functions below which is corrent.

stackoverflow says: "It looks like your post is mostly code; please add some more details." I am have not more details to says.

func sendData_Method2(data string) {

    /*
        method tcpConn.Write will be blocked until all data sent out.
    */

    addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", "127.0.0.1", 8899))
    if err != nil {
        log.Println(err)
        return
    }

    tcpConn, err := net.DialTCP("tcp", nil, addr)
    if err != nil {
        log.Println(err)
        return
    }
    defer tcpConn.Close()

    if _, err := tcpConn.Write([]byte(data)); err != nil {
        log.Println(err)
    }

}
func sendData_Method1(data string) {

    /*
        need call method tcpConn.Write in for loop until all data sent out.
    */


    addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", "127.0.0.1", 8899))
    if err != nil {
        log.Println(err)
        return
    }

    tcpConn, err := net.DialTCP("tcp", nil, addr)
    if err != nil {
        log.Println(err)
        return
    }
    defer tcpConn.Close()

    dataWillSend := []byte(data)
    lengthOfWillSend := len(dataWillSend)
    startPosi := 0

    for {
        n, err := tcpConn.Write(dataWillSend[startPosi:])
        if err != nil {
            log.Println(err)
            return
        }
        lengthOfWillSend -= n
        startPosi = n
        if lengthOfWillSend == 0 {
            break
        }
    }
}

According to io.Write documentation:

Write writes len(p) bytes from p to the underlying data stream. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. Write must return a non-nil error if it returns n < len(p).

So, you can simply call Write without a loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM