首页 > 后端开发 > Golang > 正文

Golang TCP 连接有效,但 UDP 无效

PHPz
发布: 2024-02-06 10:54:12
转载
403 人浏览过

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")
登录后复制

想要制作一个小poc来通过udp发送日志以减少积压,尝试首先建立tcp连接,它工作正常,但udp不起作用,有人可以解释我必须做什么才能使其工作吗? p>

正确答案


除非另有指定,否则 Netcat 默认情况下会创建 TCP 连接。对于 UDP 连接,您需要使用 netcat 的 -u 标志。来自 netcat 手册页

-u 使用 UDP 代替默认的 TCP 选项。

因此,将侦听器更改为 nc -luk 1902 应该可以解决 UDP 连接的问题。

以上是Golang TCP 连接有效,但 UDP 无效的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!