我使用golang开发了一个简单的利用UDP组播的示例代码,同样的代码在Linux(Fedora 34)上是可以正常接收到消息的,但是在windows10上接收不到消息。然后我用Java开发了同样的UDP组播代码,在相同的环境下,可以正常接收消息,甚至我用Golang发送消息,Java端都可以接收。此外,利用wireshark进行数据包分析,Golang和Java版本发送的IP包并无差异。问题出在了哪里?
代码如下:
package main
import (
"flag"
"fmt"
"net"
"strings"
)
var (
bind = flag.String("bind", "239.255.0.0", "bind")
port = flag.Int("port", 2222, "port")
cmd = flag.String("cmd", "server", "Command")
)
func main() {
flag.Parse()
addr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf("%s:%d", *bind, *port))
if err != nil {
panic(err)
}
switch *cmd {
case "server":
{
startServer(addr)
}
case "client":
{
startClient(addr, strings.Join(flag.Args(), ""))
}
}
}
func startServer(addr *net.UDPAddr) {
conn, err := net.ListenMulticastUDP("udp4", nil, addr)
if err != nil {
panic(err)
} else {
fmt.Println("Server was started")
}
var buff = make([]byte, 1600)
for {
l, remoteAddr, err := conn.ReadFromUDP(buff)
if err != nil {
panic(err)
}
fmt.Printf("read data from %v, data: %s\n", remoteAddr, string(buff[0:l]))
}
}
func startClient(addr *net.UDPAddr, msg string) {
conn, err := net.DialUDP("udp4", nil, addr)
if err != nil {
panic(err)
}
l, err := conn.Write([]byte(msg))
if err != nil {
panic(err)
} else {
fmt.Printf("Wrote byte length %d\n", l)
}
conn.Close()
}