package tcp import ( "fmt" "log" "net" "os" "os/signal" "syscall" ) // NewTCPServer make TCP server func NewTCPServer(addr string, cb func(*net.TCPConn)) { var ( //buffer bytes.Buffer logger = log.New(os.Stdout, "INFO: ", log.Lshortfile) ) // Interrupt handler. errc := make(chan error) go func() { c := make(chan os.Signal) signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) errc <- fmt.Errorf("%s", <-c) }() tcpaddr, err := net.ResolveTCPAddr("tcp", ":2020") if err != nil { logger.Fatalf("listen error: %v", err) return } listen, err := net.ListenTCP("tcp", tcpaddr) if err != nil { logger.Fatalf("listen error: %v", err) return } defer listen.Close() go func() { logger.Println("TCP Listen", addr) //log..Log("Protocol", "HTTP", "addr", addr) //errc <- server.ListenAndServe() for { conn, err := listen.Accept() if err != nil { errc <- err log.Fatalf("accept error: %v", err) break } tcpConn, ok := conn.(*net.TCPConn) if !ok { //error handle conn.Close() continue } go cb(tcpConn) } logger.Println("Exit server", "Quit") }() // Run! //logger.Log("Exit", <-errc) logger.Println("Exit", <-errc) }