代码
package main
import (
"fmt"
"golang.org/x/net/ipv4"
"log"
"net"
"os"
)
// 组播地址和端口
var (
multicastAddress = "224.0.0.1"
port = 8000
)
func main() {
// 绑定IP和端口
listener, err := net.ListenPacket("udp4", fmt.Sprintf("0.0.0.0:%d", port))
if err != nil {
log.Fatal(err)
}
// 关闭监听
defer listener.Close()
packConnector := ipv4.NewPacketConn(listener)
// 加入组播
if err := packConnector.JoinGroup(nil, &net.UDPAddr{IP: net.ParseIP(multicastAddress)}); err != nil {
log.Fatal(err)
}
// 离开组播
defer packConnector.LeaveGroup(nil, &net.UDPAddr{IP: net.ParseIP(multicastAddress)})
// 创建一个缓冲区(切片)用于接收数据
buffer := make([]byte, 1024*2)
go func() {
for {
// 接收数据
n, _, srcAddr, err := packConnector.ReadFrom(buffer)
if err != nil {
log.Println("Error reading:", err)
continue
}
// 打印接收到的数据和源地址
data := buffer[:n]
senderAddr := srcAddr.String()
// fmt.Printf("Received %d bytes from %s: %s\n", n, senderAddr, hex.Dump(data))
fmt.Printf("Received %d bytes from [%s]:\n%s\n", n, senderAddr, string(data))
}
}()
for {
var input string
fmt.Scanln(&input)
if input == "q" {
fmt.Println("Program exit...")
os.Exit(0)
break
}
fmt.Println(input)
}
}
效果演示