Last active
January 28, 2019 22:49
-
-
Save porjo/6494910 to your computer and use it in GitHub Desktop.
Simple PUB-SUB using multicast, written in Go. The publisher sends the string 'hello' every 2 seconds to IPv4 multicast 224.0.0.1 on UDP port 5000
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"net" | |
"time" | |
) | |
func main() { | |
mcastAddr, err := net.ResolveUDPAddr("udp", "224.0.0.1:5000") | |
if err != nil { | |
fmt.Printf("Unable to resolve multicast string, error: %s", err) | |
return | |
} | |
conn, err := net.DialUDP("udp", nil, mcastAddr) | |
if err != nil { | |
fmt.Printf("Unable to connect to multicast addr, error: %s", err) | |
return | |
} | |
wconn := bufio.NewWriter(conn) | |
for { | |
i, err := wconn.WriteString("hello\n") | |
if err != nil { | |
fmt.Printf("Write to socket %d bytes, error %s\n", i, err) | |
return | |
} | |
err = wconn.Flush() | |
if err != nil { | |
fmt.Printf("Flush socket error %s\n", err) | |
return | |
} | |
fmt.Println("hello") | |
time.Sleep(2 * time.Second) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"net" | |
"strings" | |
) | |
func main() { | |
mcastAddr, err := net.ResolveUDPAddr("udp", "224.0.0.1:5000") | |
if err != nil { | |
fmt.Printf("Unable to resolve multicast string, error: %s", err) | |
return | |
} | |
conn, err := net.ListenMulticastUDP("udp", nil, mcastAddr) | |
if err != nil { | |
fmt.Printf("Unable to bind to multicast addr, error: %s", err) | |
return | |
} | |
rconn := bufio.NewReader(conn) | |
for { | |
line, err := rconn.ReadString('\n') | |
if err != nil { | |
fmt.Printf("Read error: %s\n", err) | |
return | |
} | |
line = strings.TrimSpace(line) | |
fmt.Printf("Received: %s\n", line) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment