猿问

Golang TCP 连接有效,但 UDP 无效

我正在通过 netcat 收听 nc -lkp 1902


每当我建立 tcp 连接并尝试发送日志时,它都会工作


        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")

输出


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

但是每当我尝试建立 udp 连接时它都不起作用,谁能解释为什么我的记录器上什么也没有?


        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")

想要通过 udp 发送日志以减少积压,尝试先建立一个 tcp 连接并且它工作正常但 udp 不起作用,任何人都可以解释我必须做些什么才能让它工作吗?


婷婷同学_
浏览 107回答 1
1回答

慕雪6442864

除非另有说明,否则 Netcat 默认创建 TCP 连接。对于 UDP 连接,您需要使用-unetcat 的标志。-u 使用 UDP 而不是 TCP 的默认选项。因此,将您的侦听器更改为nc -luk 1902应该可以解决 UDP 连接的问题。
随时随地看视频慕课网APP

相关分类

Go
我要回答