Created
January 16, 2019 06:19
-
-
Save miguelmota/01ba5131838ae31947ac9b03e57f3773 to your computer and use it in GitHub Desktop.
Golang UDP server example
This file contains hidden or 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 hidden or 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