lnet
v2.0
每一層都定義了抽象的接口,只要實現相應的接口,可以方便的對每一層進行擴展。每一個介面都提供了一個基類實現,可以繼承該基類,然後重寫想要修改的方法即可。
Transport層負責網路相關的功能,目前支援TCP,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
}
Protocol層負責協定解析,目前支援ProtoBuff,Gob編碼協定
type IProtocol interface {
Marshal ( msg interface {}) ([] byte , error )
Unmarshal ( data [] byte , v interface {}) error
}
MsgHandle層負責訊息分發
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 )
}
建構一個服務只需組合上述三個層次的結構,即可客製化所需的服務
//服务器逻辑
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 )
}
}