Home >Backend Development >Golang >Golang TCP connection works but UDP doesn't

Golang TCP connection works but UDP doesn't

PHPz
PHPzforward
2024-02-06 10:54:12442browse

Golang TCP 连接有效,但 UDP 无效

Question content

I am listening through netcat nc -lkp 1902

Whenever I make a tcp connection and try to send logs, it works

timeout := 30 * time.second
    conn, err := net.dialtimeout("tcp", "localhost:1902", timeout)
    if err != nil {
        panic("failed to connect to localhost:1902")
    }
    defer conn.close()

    f := log.ldate | log.lshortfile
    logger := log.new(conn, "example-", f)
    logger.println("this is a regular message1")
    logger.println("this is a regular message2")
    logger.println("this is a regular message3")
    logger.println("this is a regular message4")
    logger.println("this is a regular message5")
    logger.println("this is a regular message6")

Output

example-2022/11/18 technique24.go:21: this is a regular message1
example-2022/11/18 technique24.go:22: this is a regular message2
example-2022/11/18 technique24.go:23: this is a regular message3
example-2022/11/18 technique24.go:24: this is a regular message4
example-2022/11/18 technique24.go:25: this is a regular message5
example-2022/11/18 technique24.go:26: this is a regular message6

But whenever I try to make a udp connection it doesn't work, can someone explain why I'm getting nothing on the logger?

timeout := 30 * time.Second
    conn, err := net.DialTimeout("udp", "localhost:1902", timeout)
    if err != nil {
        panic("Failed to connect to localhost:1902")
    }
    defer conn.Close()

    f := log.Ldate | log.Lshortfile
    logger := log.New(conn, "example-", f)
    logger.Println("This is a regular message1")
    logger.Println("This is a regular message2")
    logger.Println("This is a regular message3")
    logger.Println("This is a regular message4")
    logger.Println("This is a regular message5")
    logger.Println("This is a regular message6")

Want to make a small poc to send logs over udp to reduce the backlog, tried establishing a tcp connection first, it works fine but the udp doesn't, can someone explain what I have to do to make it work? p>

Correct answer


Netcat creates a TCP connection by default unless otherwise specified. For UDP connections, you need to use netcat's -u flag. From the netcat man page

-u Use UDP instead of the default TCP option.

So changing the listener to nc -luk 1902 should solve the problem with UDP connections.

The above is the detailed content of Golang TCP connection works but UDP doesn't. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete