lnet
v2.0
Each layer defines an abstract interface. As long as the corresponding interface is implemented, each layer can be easily extended. Each interface provides a base class implementation, which you can inherit and then override the methods you want to modify.
The Transport layer is responsible for network-related functions and currently supports TCP and WebSocket.
type ITransport interface {
GetId () uint32
GetLocalAddr () string
GetRemoteAddr () string
Listen () error
Connect () error
OnNewConnect ( transport ITransport )
Read ()
Write ()
Send ( msgPkg IMessagePackage ) error
Close ()
OnClosed ()
IsStop () bool
IsTimeout ( tick * time. Timer ) bool
}
The Protocol layer is responsible for protocol analysis and currently supports ProtoBuff and Gob encoding protocols.
type IProtocol interface {
Marshal ( msg interface {}) ([] byte , error )
Unmarshal ( data [] byte , v interface {}) error
}
MsgHandle layer is responsible for message distribution
type IMsgHandle interface {
RegisterMsg ( tag uint32 , msg interface {})
NewMsg ( tag uint32 ) interface {}
GetMsgTag ( msg interface {}) uint32
SetProtocol ( protocol IProtocol )
GetProtocol () IProtocol
CreateMessage ( msgPkg IMessagePackage ) interface {}
CreateMessagePackage ( msg interface {}) IMessagePackage
Process ( transport ITransport , msgPackage IMessagePackage )
SetOnTransportClose ( f func ( transport ITransport ))
OnTransportClose ( transport ITransport )
}
To build a service, you only need to combine the above three levels of structure to customize the required service.
//服务器逻辑
func serverStart () {
//选择协议
protocol := & lprotocol. PbProtocol {}
//选择消息处理函数
msgHandle := lmsghandle . NewBaseMsgHandle ( protocol )
//注册消息
msgHandle . RegisterMsg ( 12 , pb. GameItem {})
msgHandle . RegisterMsg ( 13 , pb. RpcReqData {})
msgHandle . RegisterMsg ( 14 , pb. RpcRspData {})
//启动服务
server := lserver . NewTcpServer ( "127.0.0.1:9000" , msgHandle )
server . Start ()
}
//客户端逻辑
func clientStart () {
//选择协议
protocol := & lprotocol. PbProtocol {}
//选择消息处理函数
msgHandle := lmsghandle . NewBaseMsgHandle ( protocol )
//注册消息
msgHandle . RegisterMsg ( 12 , pb. GameItem {})
msgHandle . RegisterMsg ( 13 , pb. RpcReqData {})
msgHandle . RegisterMsg ( 14 , pb. RpcRspData {})
client := lclient . NewTcpClient ( "127.0.0.1:9000" , msgHandle )
client . Connect ()
msg := & pb. GameItem { Id : 1 , Type : 2 , Count : 3 }
for {
client . Send ( msg )
time . Sleep ( 1 * time . Second )
}
}