加入upnp多播组(239.255.255.250:1900)
golang的udp组播, 如果你家里有路由器,可以试一下。
package main import ( "bufio" "bytes" "log" "net" "net/http" "regexp" ) func handler(r *http.Request) { log.Printf("Got %s %s message from %v: %v", r.Method, r.URL.Path, r.RemoteAddr, r.Header) } var ( trailingWhitespaceRx = regexp.MustCompile(" +\r\n") crlf = []byte("\r\n") ) // 加入upnp多播组: 239.255.255.250:1900 func main() { var addr *net.UDPAddr var err error if addr, err = net.ResolveUDPAddr("udp", "239.255.255.250:1900"); err != nil { log.Fatal(err) } var conn net.PacketConn // net.Interface is nil, call net.joinIPv4Group if conn, err = net.ListenMulticastUDP("udp", nil, addr); err != nil { log.Fatal(err) } log.Println("begin to receive: ") buf := make([]byte, 2048) for { n, peerAddr, err := conn.ReadFrom(buf[0:]) log.Println("n=", n) if err != nil { log.Fatal(err) break } reqbytes := buf[:n] reqbytes = trailingWhitespaceRx.ReplaceAllLiteral(reqbytes, crlf) req, err := http.ReadRequest(bufio.NewReader(bytes.NewBuffer(reqbytes))) if err != nil { log.Printf("Failed to parse request: %v", err) return } req.RemoteAddr = peerAddr.String() handler(req) } }