duanmoen784988 2014-11-28 00:15
浏览 48
已采纳

为什么我的UDP拨号程序也没有监听?

I have two programs, a listener and a dialer. I want a two way street of UDP communication on the same port. My Listener as expected reads the datagram sent from the dialer, then sends back 5 datagrams of its own. Only trouble is, my dialer isn't reading it.

I tried using net.DialUDP but when I use that, 0 datagrams get sent from the dialer.

listener - Works great

func main() {

addr := net.UDPAddr{
    Port: 7000,
    IP:   net.ParseIP("127.0.0.1"),
}
conn, err := net.ListenUDP("udp", &addr)

defer conn.Close()
if err != nil {
    panic(err)
}

i := 0

b := make([]byte, 10)
conn.ReadFromUDP(b)
fmt.Println(string(b[:]))
for i < 5 {

    conn.WriteToUDP([]byte("sending back"), &addr)
    i++
}
}

Dialer that sends datagram but cannot read them

func main() {
sock, _ := net.Dial("udp", "127.0.0.1:7000")
buf := make([]byte, 100)

_, werr := sock.Write([]byte("first send"))
if werr != nil {
    fmt.Println(werr)
}
sock.Read(buf)

fmt.Println(string(buf[:]))
}

Dialer that doesn't send any datagrams

func main() {

remote, _ := net.ResolveUDPAddr("udp", "127.0.0.1:7000")
sock, _ := net.DialUDP("udp", nil, remote)

buf := make([]byte, 10)

for {
    sock.WriteToUDP([]byte("first send"), remote)
    sock.ReadFromUDP(buf)
    fmt.Println(string(buf[:]))

}
}
  • 写回答

1条回答 默认 最新

  • dongsui5464 2014-11-28 02:24
    关注

    When in doubt, just use ListenUDP. It will both send and receive datagrams.

    sock, _ := net.Dial("udp", "127.0.0.1:7000")
    

    This creates a net.Conn, which is only a basic connection interface. You have to assert it as a *net.UDPConn to get the actual UDP methods to work.

    sock, _ := net.DialUDP("udp", nil, remote)
    

    This creates a "connected" UDP socket, and uses the bare Write method to send to a single remote address.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: