package main import ( "fmt" "log" "net" "os" "os/signal" "runtime" "syscall" "time" "github.com/gansidui/gotcp" "github.com/gansidui/gotcp/examples/echo" ) type Callback struct{} func (this *Callback) OnConnect(c *gotcp.Conn) bool { addr := c.GetRawConn().RemoteAddr() c.PutExtraData(addr) fmt.Println("OnConnect:", addr) return true } func (this *Callback) OnMessage(c *gotcp.Conn, p gotcp.Packet) bool { echoPacket := p.(*echo.EchoPacket) fmt.Printf("OnMessage:[%v] [%v]\n", echoPacket.GetLength(), string(echoPacket.GetBody())) c.AsyncWritePacket(echo.NewEchoPacket(echoPacket.Serialize(), true), time.Second) return true } func (this *Callback) OnClose(c *gotcp.Conn) { fmt.Println("OnClose:", c.GetExtraData()) } func main() { runtime.GOMAXPROCS(runtime.NumCPU()) // creates a tcp listener tcpAddr, err := net.ResolveTCPAddr("tcp4", ":8989") checkError(err) listener, err := net.ListenTCP("tcp", tcpAddr) checkError(err) // creates a server config := &gotcp.Config{ PacketSendChanLimit: 20, PacketReceiveChanLimit: 20, } srv := gotcp.NewServer(config, &Callback{}, &echo.EchoProtocol{}) // starts service go srv.Start(listener, time.Second) fmt.Println("listening:", listener.Addr()) // catchs system signal chSig := make(chan os.Signal) signal.Notify(chSig, syscall.SIGINT, syscall.SIGTERM) fmt.Println("Signal: ", <-chSig) // stops service srv.Stop() } func checkError(err error) { if err != nil { log.Fatal(err) } }