High performance network library,especially for game servers
- MultiThread, nonblocking
- Default support protobuf
- Optimize receiving and dispatching using lockless RingBuffer, which can improve performance by 5x for some cases
- Easy to implement custom encoding and decoding
- rpc
- Support Tcp,WebSocket(ws and wss)
run a server
codec := gnet.NewProtoCodec(nil)
handler := gnet.NewDefaultConnectionHandler(codec)
handler.Register(gnet.PacketCommand(pb.CmdTest_Cmd_TestMessage), onTestMessage, new(pb.TestMessage))
listenerConfig := &gnet.ListenerConfig{
AcceptConfig: gnet.DefaultConnectionConfig,
}
listenerConfig.AcceptConfig.Codec = codec
listenerConfig.AcceptConfig.Handler = handler
gnet.GetNetMgr().NewListener(ctx, "localhost:10001", listenerConfig)
run a client
codec := gnet.NewProtoCodec(nil)
handler := gnet.NewDefaultConnectionHandler(codec)
handler.Register(gnet.PacketCommand(pb.CmdTest_Cmd_TestMessage), onTestMessage, new(pb.TestMessage))
connectionConfig := gnet.DefaultConnectionConfig
connectionConfig.Codec = clientCodec
connectionConfig.Handler = clientHandler
connector := gnet.GetNetMgr().NewConnector(ctx, "localhost:10001", &connectionConfig, nil)
connector.SendPacket(gnet.NewProtoPacket(gnet.PacketCommand(pb.CmdTest_Cmd_TestMessage),
&pb.TestMessage{
Name: "hello",
}))
Encoding and decoding(https://github.com/fish-tennis/gnet/blob/main/codec.go)
gnet divide TCP stream based decoding into three layers
Layer1:subcontracting stream, format:|Length|Data|,after receiving full packet content, hand it over to the next layer for processing
Layer2:Decoding the data from Layer1,such as decryption,decompression,etc
Layer3:protobuf deserialize,generate proto.Message
Rpc send a request to target and block wait reply,similar to grpc-go,but gnet use command id instead of method name
request := gnet.NewProtoPacket(cmd, &pb.HelloRequest{
Name: "hello",
})
reply := new(pb.HelloReply)
err := connection.Rpc(request, reply)
if err != nil {
return
}
logger.Info("reply:%v", reply)
example/helloworld: a simple example use protobuf message
example/data_packet: a simple example use DataPacket
example/custom_packet: how to extend custom packet struct
example/tcp_connection_simple: use protobuf message without RingBuffer
example/packet_size: send big packet which size is bigger than RingBuffer's cap
example/websocket: a simple example use websocket
example/rpc: how to use rpc
example/simulate_game: a performance test with a game application scenario
C#: gnet_csharp
distributed game server framework
gnet is also used in our commercial online game projects