登录
首页 >  Golang >  Go问答

Golang中实现点对点UDP通信

来源:stackoverflow

时间:2024-03-01 15:09:20 305浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《Golang中实现点对点UDP通信》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我有一个分布式应用程序,它在多个对等点之间发送消息。我已经从 tcp 切换到 udp。我已经看到 udp 可以使用单个套接字发送和接收,因此我尝试使用包含单个套接字的每个服务器来实现该应用程序。

我已经设置了一小段代码来测试这一点,但当尝试在 udpc 上调用 writetoudp 时,它会返回 ehostunreach (65)

Id // assumed to be a unique for the server
PeerAddrList // assumed to be a slice of all server locations (addr:port strings)
N // assumed to be the number of servers

laddr, _ := net.ResolveUDPAddr("udp", PeerAddrList[Id])
UDPC, er := net.ListenUDP("udp", laddr)
if er != nil {
    panic(er)
}

for i := 0; i < N; i++ {
    if i == int(Id) {
        continue
    }
    i := i
    go func() {
        var b [4]byte
        bs := b[:4]
        binary.LittleEndian.PutUint32(bs, uint32(Id))
        radddr, _ := net.ResolveUDPAddr("udp", PeerAddrList[i])
        if _, er := UDPC.WriteToUDP(bs, radddr); er != nil { 
            panic(er)
        }
    }()
}

for i := 0; i < N; i++ {
    if i == int(Id) {
        continue
    }
    var b [4]byte
    bs := b[:4]
    _, raddr, e := UDPC.ReadFromUDP(bs)
    if e != nil {
        panic(e)
    }
    // check if laddr == id
    id := int32(binary.LittleEndian.Uint32(bs))
    log.Printf("Got id %d from %s", id, raddr.String())
}

任何关于为什么这种行为与我的预期不同或如何解决它的建议,我们将不胜感激。


正确答案


我发现问题存在的原因是我正在测试我的环回地址,但没有在 PeerAddrList 中指定地址,只指定“:PORT”。当将地址指定为“127.0.0.1:PORT”时,UDP 套接字上的 SendTo 有效

理论要掌握,实操不能落!以上关于《Golang中实现点对点UDP通信》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>