/gnet

high performance net library for game server

Primary LanguageGoMIT LicenseMIT

gnet

Go Report Card Go Reference codecov Mentioned in Awesome Go

中文说明

High performance network library,especially for game servers

Features

  • 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
  • Support Tcp,WebSocket(ws and wss)

Core module

Listen to a certain port, start a listening goroutine, and manage the connected connections

create a Listener:

netMgr.NewListener("127.0.0.1:10001", connectionConfig, codec, &echoServerHandler{}, &echoListenerHandler{})

There are two types of connection:

  • connector(call Connect() to connect the server)
  • accept by listener(the server call accept() to accept a new connection)

create a Connector:

netMgr.NewConnector("127.0.0.1:10001", connectionConfig, codec, &echoClientHandler{}, nil)

The common practices in game servers,the packet consists of a message number and a proto message,meanwhile gnet reserve a binary interface

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

length & data

encode

decode

ListenerHandler:when the server accept a new connection or the accepted connection disconnected

ConnectionHandler:when the connection connected,disconnected,receive packet

gnet provided a default ConnectionHandler:

handler := NewDefaultConnectionHandler(codec)
// register packet and process function
handler.Register(123, OnTest, new(pb.TestMessage))
func OnTest(conn Connection, packet Packet) {
    testMessage := packet.Message().(*pb.TestMessage)
    // do something
}

Use RingBuffer to increase performance

ringbuffer-performance

goroutine

connection_goroutine

Examples

echo with protobuf

echo without protobuf

custom packet struct

simulate performance testing of a simple game server scenario

tcp without ringbuffer

websocket

Client Connector Library

C#: gnet_csharp

Project

game db&cache framework

distributed game server framework

gnet is also used in our commercial online game projects