123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- package tcp
- import (
- "fmt"
- "log"
- "net"
- "os"
- "os/signal"
- "syscall"
- )
- // NewTCPServer make TCP server
- func NewTCPServer(addr string, cb func(*net.TCPConn)) {
- logger := log.New(os.Stdout, "INFO: ", log.LstdFlags)
- 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", addr)
- 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)
- for {
- conn, err := listen.AcceptTCP()
- if err != nil {
- errc <- err
- logger.Fatalf("accept error: %v", err)
- break
- }
- go cb(conn)
- }
- logger.Println("Exit server", "Quit")
- }()
- logger.Println("TCP Service Exit", <-errc)
- }
|