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
}
프로토콜 계층은 프로토콜 분석을 담당하며 현재 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 )
}
}