server.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package tcp
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "os"
  7. "os/signal"
  8. "syscall"
  9. )
  10. // NewTCPServer make TCP server
  11. func NewTCPServer(addr string, cb func(*net.TCPConn)) {
  12. var (
  13. //buffer bytes.Buffer
  14. logger = log.New(os.Stdout, "INFO: ", log.Lshortfile)
  15. )
  16. // Interrupt handler.
  17. errc := make(chan error)
  18. go func() {
  19. c := make(chan os.Signal)
  20. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  21. errc <- fmt.Errorf("%s", <-c)
  22. }()
  23. tcpaddr, err := net.ResolveTCPAddr("tcp", ":2020")
  24. if err != nil {
  25. logger.Fatalf("listen error: %v", err)
  26. return
  27. }
  28. listen, err := net.ListenTCP("tcp", tcpaddr)
  29. if err != nil {
  30. logger.Fatalf("listen error: %v", err)
  31. return
  32. }
  33. defer listen.Close()
  34. go func() {
  35. logger.Println("TCP Listen", addr)
  36. //log..Log("Protocol", "HTTP", "addr", addr)
  37. //errc <- server.ListenAndServe()
  38. for {
  39. conn, err := listen.Accept()
  40. if err != nil {
  41. errc <- err
  42. log.Fatalf("accept error: %v", err)
  43. break
  44. }
  45. tcpConn, ok := conn.(*net.TCPConn)
  46. if !ok {
  47. //error handle
  48. conn.Close()
  49. continue
  50. }
  51. go cb(tcpConn)
  52. }
  53. logger.Println("Exit server", "Quit")
  54. }()
  55. // Run!
  56. //logger.Log("Exit", <-errc)
  57. logger.Println("Exit", <-errc)
  58. }