DelayNoMore/udp_server_prac/main.go

40 lines
748 B
Go
Raw Normal View History

package main
import (
"fmt"
"net"
"strings"
)
func main() {
conn, err := net.ListenUDP("udp", &net.UDPAddr{
Port: 3000,
IP: net.ParseIP("127.0.0.1"),
})
if err != nil {
panic(err)
}
defer conn.Close()
fmt.Printf("server listening %s\n", conn.LocalAddr().String())
for {
message := make([]byte, 2046)
rlen, remote, err := conn.ReadFromUDP(message[:])
if err != nil {
panic(err)
}
data := strings.TrimSpace(string(message[:rlen]))
fmt.Printf("received: %d bytes, content=%s from %s\n", rlen, data, remote)
// echo
rlen, wrerr := conn.WriteTo(message[0:rlen], remote)
if wrerr != nil {
fmt.Printf("net.WriteTo() error: %s\n", wrerr)
} else {
fmt.Printf("Wrote %d bytes to socket\n", rlen)
}
}
}