- An universal multi-layer tcp client 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-client-agent
Or run directly
$ make run
- Main code usage
//define config info to connect to remote server.
cfg := &model.Config{
Id: 0,
Host: "127.0.0.1",
Port: 1922,
}
//create a tcp client then begin to run.
if agent := core.NewTcpClient(cfg); agent != nil {
agent.Run()
defer agent.Shutdown()
}
- Receive message from server
In the
core/agent.go
, focus on theinitHandlers
function. Add your own message handler for different message id there.
func (cli *GtaTcpClient) initHandlers() {
cli.handlers = make(map[uint16]gtaMsgHandler)
// Add your own msg handler here.
//e.g.
cli.addHandler(101, cli.onHandleMyFirstAck)
}
func (cli *GtaTcpClient) onHandleMyFirstAck(msgID uint16, payload []byte, len int) error {
//Deserialize data in your own protocol.
ack := &msg.MyFirstAck{}
proto.Unmarshal(payload, ack)
//...
return nil
}
- Send message to server
In the
core/agent.go
, usingGtaTcpClient.conn.Send()
function to send message.
func (cli *GtaTcpClient) register() error {
//Call cli.conn.Send() to send your own message to server.
req := &msg.MyFirstReq{
Hello: []byte("hello"),
}
err := cli.conn.Send(100, req)
return err
}