-
-
Save wfairclough/20c98035f05fef529f958ad0866abe2d to your computer and use it in GitHub Desktop.
Golang UDP server example
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
echo 'hello world' > /dev/udp/0.0.0.0/3000 |
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 ( | |
"fmt" | |
"net" | |
"strings" | |
) | |
func main() { | |
conn, err := net.ListenUDP("udp", &net.UDPAddr{ | |
Port: 3000, | |
IP: net.ParseIP("0.0.0.0"), | |
}) | |
if err != nil { | |
panic(err) | |
} | |
defer conn.Close() | |
fmt.Printf("server listening %s\n", conn.LocalAddr().String()) | |
for { | |
message := make([]byte, 20) | |
rlen, remote, err := conn.ReadFromUDP(message[:]) | |
if err != nil { | |
panic(err) | |
} | |
data := strings.TrimSpace(string(message[:rlen])) | |
fmt.Printf("received: %s from %s\n", data, remote) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment