main.go 922 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package main
  2. import (
  3. "flag"
  4. "log"
  5. "net"
  6. "os"
  7. "os/signal"
  8. )
  9. func main() {
  10. port := flag.String("p", "8125", "Listening port")
  11. stdLogger := log.New(os.Stdout, "", log.LstdFlags|log.Lmsgprefix)
  12. flag.Parse()
  13. if flag.NArg() > 0 {
  14. flag.PrintDefaults()
  15. return
  16. }
  17. addr, err := net.ResolveUDPAddr("udp", ":"+*port)
  18. if err != nil {
  19. panic(err)
  20. }
  21. listener, err := net.ListenUDP("udp", addr)
  22. if err != nil {
  23. panic(err)
  24. }
  25. defer listener.Close()
  26. stdLogger.Printf("Server started and listen on port %s...", *port)
  27. c := make(chan os.Signal, 1)
  28. signal.Notify(c, os.Interrupt)
  29. go func() {
  30. buf := make([]byte, 10240)
  31. for {
  32. n, addr, err := listener.ReadFromUDP(buf)
  33. if err != nil {
  34. stdLogger.Printf("Error receiving packet: %v", err)
  35. continue
  36. }
  37. stdLogger.Printf("Received: %q from %s", string(buf[0:n]), addr)
  38. }
  39. }()
  40. <-c
  41. stdLogger.Println("Received interrupt signal. Exiting...")
  42. }