socket_protobuf
English:
Under the nodejs running environment, this SDK is used for socket sends the protobuf binary stream.
The open source code has an example, you can download the code to see how to use.
author email:597785841@qq.com
example:
socket server backend:
Server.ts
const server1:ServerListener = new ServerListener( 4001 );
/*通信协议/
export enum Cmd
{
Login = 1,
handler2 = 2,
handler3 = 3
}
const setHandler:( cmdId:number, handler:Handler )=>void = server1.handlerMgr.setHandler.bind( server1.handlerMgr );
setHandler( Cmd.Login, new LoginHandler() );
setHandler( Cmd.handler2, new Handler2() );
setHandler( Cmd.handler3, new Handler3() );
server1.startServer( onConnectClient, onDisconnectClient );
function onConnectClient(client: ClientSocket):void
{
console.log( 服务器 1 新增连接,socket id:
+ client.id );
}
function onDisconnectClient(socketId: number, client: ClientSocket):void
{
console.log( 服务器 1 ${socketId==client.id?"正常":"异常"}断开连接,socket id:
+ client.id );
}
console.log( 本机IPv4:${ServerListener.GetIP()}
);
console.log( 本机IPv6:${ServerListener.GetIP(false )}
);
socket server backend Handler example, LoginHandler.ts :
export class LoginHandler extends Handler
{
public async execute( cmdId:number, socketId:number, u8a:Uint8Array ):Promise
{
const login:PUser = PUser.decode( u8a );
console.log( login.account, login.password );
const success:PLoginSuccess = new PLoginSuccess({
sex:"男",
name:"Gordon",
age:18
} );
this.send( Cmd.Login, socketId, PLoginSuccess.encode( success ).finish() );
}
}
socket client frontend:
UserClient.ts
const userClient:Client = new Client({
ip:"127.0.0.1",
port:4001,
time:3
} );
/*通信协议/
export enum Cmd
{
Login = 1,
handler2 = 2,
handler3 = 3
}
const onServerInfo = ( server:PServer ):void=>
{
console.log( JSON.stringify( server.toJSON() ) );
const user:PUser = new PUser( {
account:"root",
password:"123456"
} );
userClient.send( Cmd.Login, PUser.encode( user ).finish() );
};
const onConnected = ():void=>
{
console.log( client连接socket成功
);
};
userClient.startConnect( onServerInfo, null, onConnected );
let setHandler:( cmdId:number, handler:Handler )=>void;
setHandler = userClient.handlerMgr.setHandler.bind( userClient.handlerMgr );
setHandler( Cmd.Login, new LoginSuccessHandler() );
setHandler( Cmd.handler2, new Handler2() );
setHandler( Cmd.handler3, new Handler3() );
socket client frontend Handler example, LoginSuccessHandler.ts :
export class LoginSuccessHandler extends Handler
{
public async execute( cmdId:number, u8a:Uint8Array ):Promise
{
const login:PLoginSuccess = PLoginSuccess.decode( u8a );
console.log( login.name, login.age, login.sex );
}
}
中文:
在nodejs运行环境下,socket发送protobuf二进制流的SDK。
源码有例子,可以下载源码查看使用方法。
作者邮箱:597785841@qq.com
由于github源码无法访问,中国大陆源码地址如下:
https://e.coding.net/wujinhong/open_source/socket_protobuf.git