Created
March 29, 2015 16:07
-
-
Save alexanderGugel/ee1e25dbab61bf2d521d to your computer and use it in GitHub Desktop.
PING server using Go
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
// Start using | |
// go run ping.go -addr=:3141 | |
// Query using | |
// nc -u localhost 3141 | |
package main | |
import ( | |
"log" | |
"net" | |
"flag" | |
"bytes" | |
) | |
func main() { | |
addr := flag.String("addr", "localhost:0", "addr") | |
flag.Parse() | |
// resolve address | |
ServerAddr, err := net.ResolveUDPAddr("udp", *addr) | |
if err != nil { | |
log.Fatal("Couldn't resolve passed in addr ", err) | |
} | |
// start listening | |
ServerConn, err := net.ListenUDP("udp", ServerAddr) | |
if err != nil { | |
log.Fatal("Couldn't listen on passed in addr " , err) | |
} | |
log.Println("Listening on", ServerConn.LocalAddr().String()) | |
// close connection as soon as program exists | |
defer ServerConn.Close() | |
// used for incoming messages | |
buf := make([]byte, 1024) | |
PING := []byte("PING\n") | |
PONG := []byte("PONG\n") | |
for { | |
n, addr, err := ServerConn.ReadFromUDP(buf) | |
log.Println("Received ", string(buf[0:n]), " from ", addr) | |
if err != nil { | |
log.Println("Error: ", err) | |
} | |
if bytes.Equal(buf[:len(PING)], PING) { | |
ServerConn.WriteTo(PONG, addr) | |
continue | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment