- An universal multi-layer tcp server framework.
- Universal interface
ILogger
andIParser
, support custom middleware for logger and parser. - Support kinds of message protocol, such as proto, thrift, json, xml etc.
- Provide event queue injection, decouple business logic and network layer.
- Seperate send and receive using channel.
- Sync connection state in multiple goroutine.
- Golang v1.11+ Tested (go mod suppored)
- Protoc & Protoc-gen-go
$ go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
The example instance using proto, follow the steps to run:
- Download dependecies
$ go mod download
- Generate proto message
$ ./genmsg.sh
It will auto convert .pb
files under core/proto/msg to .pb.go
- Build and run
$ make build
$ ./build/go-tcp-server-agent
Or run directly
$ make run
- Main code usage
//define config info for current server.
cfg := &model.Config{
Id: 1000,
Host: "127.0.0.1",
Port: 1922,
}
//create a tcp server then begin to run.
if agent := core.NewTcpServer(cfg); agent != nil {
agent.Run()
defer agent.Shutdown()
}
- Receive request and send response message
In the
core/agent.go
, focus on theinitHandlers
function. Add your own message handler for different message id there.
func (svr *GtaTcpServer) initHandlers() {
svr.handlers = make(map[uint16]gtaMsgHandler)
// Add your own msg handler here.
//e.g.
svr.addHandler(100, svr.onHandleMyFirstReq)
}
func (svr *GtaTcpServer) onHandleMyFirstReq(c *service.GtaConnection, msgID uint16, payload []byte, len int) error {
req := &msg.MyFirstReq{}
if err := proto.Unmarshal(payload, req); err != nil {
return err
}
ack := &msg.MyFirstAck{
Word: []byte(string(req.Hello) + "world"),
}
err := c.Send(101, ack)
return err
}