Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang tcp socket does not send message after write immediately

Tags:

tcp

go

sockets

My GO version is 1.1.1

the sever recieved messages after connection close, but NoDelay was setted.

Is there something wrong

addr, _ := net.ResolveTCPAddr("tcp", "localhost:5432")
conn, err := net.DialTCP("tcp", nil, addr)
defer conn.Close()
if err != nil {
    fmt.Println("connect fail")
    return
}
err = conn.SetNoDelay(true)
if err != nil {
    fmt.Println(err.Error())
}

for {
    var message string
    _, err := fmt.Scanln(&message)
    if err != nil && err.Error() != "unexpected newline" {
        fmt.Println("input finished", err)
        break
    }

    if message == "" {
        fmt.Println("no input, end")
        break
    }
    // message = fmt.Sprintf("%s\n",message) 
    //fmt.Fprintf(conn, message) // send immediately but following message won't send any more
    conn.Write([]byte(message)) // won't send until connection close
}
like image 349
enzoyang Avatar asked Mar 23 '23 00:03

enzoyang


1 Answers

There doesn't seem to be anything vitally wrong with your code so I'm guessing the error is on the server end.

If you create a local TCP server on port 5432 you can test this.

Try running the below server code and then test your client code against it. It just echos all received data to stdout.

package main

import (
    "io"
    "log"
    "net"
    "os"
)

func main() {
    l, err := net.Listen("tcp", "localhost:5432")
    if err != nil {
        log.Fatal(err)
    }
    defer l.Close()
    for {
        conn, err := l.Accept()
        if err != nil {
            log.Fatal(err)
        }
        go func(c net.Conn) {
            defer c.Close()
            io.Copy(os.Stdout, c)
        }(conn)
    }
}

You should see each line sent to the client printed (without the newline) as soon as you hit enter.

like image 85
Intermernet Avatar answered Apr 07 '23 17:04

Intermernet