前言
nodejs游戏服务器开发系列文章以nodejs+Typescript+CocosCreator+WebSocket为例,搭建服务器和客户端。
下面我们以一个聊天系统为例,把客户端和服务端流程走一遍。
最终的聊天系统已经托管在git上了:https://github.com/iningwei/nodejs-CocosCreator-websocket
proto文件及系统流程
message Role{
required string roleName=1;
}
message ChatData{
required string content=1;
required string dateTime=2;//时间戳
required Role sender=3;//发送者
}
//msgID=10001
message LoginReq{
required Role role=1;
}
//msgID=10002
message LoginRes{
required int32 result=1;//0为失败,1为成功
}
//msgID=10011
message ChatReq{
required ChatData chatData=1;
}
//msgID=10012
message ChatRes{
required int32 result=1;//0为失败,1为成功
required ChatData chatData=2;
}
该系统的流程是:
客户端启动后,本地会为其随机roleName,在客户端连上服务器后,会发送LoginReq消息,请求登录。
客户端可以发送ChatReq消息,服务器收到后进行广播。
为了能够识别消息类型,我为每个消息在前面加了4个字节的消息号。
客户端代码如下
@property(cc.Label)
nameLbl: cc.Label;
@property(cc.Node)
chatContentRoot: cc.Node;
@property(cc.Node)
chatItemPrefab: cc.Node;
@property(cc.EditBox)
editBox: cc.EditBox;
private roleName: string;
private role: proto.Role;
private ws: WebSocket;
start() {
this.roleName = "jack" + Math.floor(Math.random() * 10000);
this.nameLbl.string = this.roleName;
this.role = new proto.Role();
this.role.roleName = this.roleName;
this.ws = new WebSocket("ws://192.168.2.31:8083");
this.ws.binaryType = "arraybuffer";
this.ws.onopen = this.onOpen.bind(this);
this.ws.onmessage = (event) => {
// console.log("client rcv:" + event.data);// event.data若是二进制,为:ArrayBuffer类型
this.unSerialize(event.data);
}
this.ws.onclose = function (event) {
}.bind(this);
this.ws.onerror = function (event) {
}
}
private onOpen(event: MessageEvent) {
console.log("和服务器连接建立啦");
this.reqLogin();
}
private reqLogin() {
let loginReq = new proto.LoginReq();
loginReq.role = this.role;
console.log("sedMsg:10001, " + JSON.stringify(loginReq.toJSON()));
let encodedBuf: Uint8Array = proto.LoginReq.encode(loginReq).finish();//编码后必须调用finish(),否则类型不对
this.ws.send(this.serialize(10001, encodedBuf));
}
private unSerialize(arrayBuf: ArrayBuffer) {
let dv = new DataView(arrayBuf);
//获得消息号
let msgId = dv.getInt32(0);//TODO:大小端问题。dv.getInt32(0,true);
//获得消息体
let body: Uint8Array = new Uint8Array(arrayBuf, 4);
let data: any = null;
switch (msgId) {
case 10002:
data = proto.LoginRes.decode(body);
break;
case 10012:
data = proto.ChatRes.decode(body);
if (data.result === 1) {
this.addChatItem((<proto.ChatRes>data).chatData);
}
break;
}
console.log("rcvMsg: " + msgId + ", " + JSON.stringify(data.toJSON()));
}
private serialize(msgId: number, bodyArray: Uint8Array): ArrayBuffer {
let totalLen = 4;
totalLen += (bodyArray.length * 1);//Uint8为一个字节
//写入消息号
let buf = new ArrayBuffer(totalLen);
let dataView = new DataView(buf);
dataView.setInt32(0, msgId);
let offset = 4;
//写入消息体
for (let i = 0; i < bodyArray.length; i++) {
const element = bodyArray[i];
dataView.setUint8(offset, element);
offset += 1;
}
return dataView.buffer;
}
public SendChat() {
let content = this.editBox.string.trim();
if (content == "") {
console.log("请输入聊天文字");
return;
}
let chatReq = new proto.ChatReq();
chatReq.chatData = new proto.ChatData();
chatReq.chatData.content = content;
chatReq.chatData.dateTime = new Date().toTimeString().split(" ")[0];
chatReq.chatData.sender = this.role;
let encodedBuf: Uint8Array = proto.ChatReq.encode(chatReq).finish();
this.ws.send(this.serialize(10011, encodedBuf));
this.editBox.string = "";
}
private addChatItem(data: proto.IChatData) {
let chatNode = cc.instantiate(this.chatItemPrefab);
chatNode.parent = this.chatContentRoot;
chatNode.active = true;
let str = data.sender.roleName + " " + data.dateTime + " " + data.content;
chatNode.getComponent(cc.Label).string = str;
}
服务端
import * as WebSocket from "ws"
import proto = require("./pb/proto");
const server = new WebSocket.Server({ port: 8083 });
server.on("listening", () => {
console.log("服务器启动完毕!开始侦听");
});
server.on("connection", function connection(ws, req) {
const ip = req.connection.remoteAddress;
console.log(ip + " 连接上服务器");
ws.on("message", (data) => {
console.log("received:%s,类型:%s", data, (typeof data));
//虽然客户端那边传的时候是ArrayBuffer类型,但是经过调试到这里data类型为buffer,需要转换为ArrayBuffer
let arrayBuf: ArrayBuffer = toArrayBuffer(data);
let r = unSerialize(arrayBuf);
if (r.msgId === 10001) {
let loginRes = new proto.LoginRes();
loginRes.result = 1;
console.log("sedMsg:10002, " + JSON.stringify(loginRes.toJSON()));
let encodedBuf: Uint8Array = proto.LoginRes.encode(loginRes).finish();
ws.send(serialize(10002, encodedBuf));
}
else if (r.msgId === 10011) {
let chatRes = new proto.ChatRes();
chatRes.result = 1;
chatRes.chatData = (<proto.ChatReq>(r.data)).chatData;
console.log("sedMsg:10012, " + JSON.stringify(chatRes.toJSON()));
let encodedBuf: Uint8Array = proto.ChatRes.encode(chatRes).finish();
server.clients.forEach(function each(client) {
client.send(serialize(10012, encodedBuf));
});
}
});
});
function unSerialize(arrayBuf: ArrayBuffer): { msgId: number, data: any } {
let dv = new DataView(arrayBuf);
//获得消息号
let id = dv.getInt32(0);//TODO:大小端问题。dv.getInt32(0,true);
//获得消息体
let body: Uint8Array = new Uint8Array(arrayBuf, 4);
let result: any = null;
switch (id) {
case 10001:
result = proto.LoginReq.decode(body);
break;
case 10011:
result = proto.ChatReq.decode(body);
break;
}
console.log("rcvMsg: " + id + ", " + JSON.stringify(result.toJSON()));
return { msgId: id, data: result };
}
function serialize(msgId: number, bodyArray: Uint8Array): ArrayBuffer {
let totalLen = 4;
totalLen += (bodyArray.length * 1);//Uint8为一个字节
//写入消息号
let buf = new ArrayBuffer(totalLen);
let dataView = new DataView(buf);
dataView.setInt32(0, msgId);
let offset = 4;
//写入消息体
for (let i = 0; i < bodyArray.length; i++) {
const element = bodyArray[i];
dataView.setUint8(offset, element);
offset += 1;
}
return dataView.buffer;
}
//Buffer转ArrayBuffer
function toArrayBuffer(buf) {
var ab = new ArrayBuffer(buf.length);
var view = new Uint8Array(ab);
for (var i = 0; i < buf.length; ++i) {
view[i] = buf[i];
}
return ab;
}
//ArrayBuffer转Buffer
function toBuffer(ab) {
var buf = new Buffer(ab.byteLength);
var view = new Uint8Array(ab);
for (var i = 0; i < buf.length; ++i) {
buf[i] = view[i];
}
return buf;
}
总结
上述演示了一个聊天系统的基础实现流程。在不考虑断线重连等情况下,仍然还有很多需要优化的地方。
比如:
1:服务器在收到ChatReq后是直接转发给所有连上的客户端。根据本实例,应该是转发给所有Login成功的客户端。
2:消息号应该枚举化,统一管理,注册。本例中分散的把消息号写到各个逻辑功能中,耦合性太高。不利于维护,且容易出错。
3:需要维护一个消息分发系统,各个功能模块通过对消息进行监听,来实现业务逻辑。
4:消息的序列化,反序列化代码不够简练,需要进一步优化。