本文主要是介绍CocosCreator Websocket简单使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最近在官方文档里看到网络模块相关内容,于是自己写了一个用websocket实现的聊天室Demo,分享一下。
服务端:基于node.js的websocket模块实现。
WebsocketServer.js
let ws = require("nodejs-websocket");let server = ws.createServer((connection)=>{connection.on("text", (data)=>{console.log('收到客户端消息:', data);//遍历所有连接的客户端,发送消息server.connections.forEach((conn)=>{conn.send(data);});});connection.on("close", (code)=>{console.log('关闭连接:' + code);});connection.on("error", (code, reason)=>{console.log("异常关闭")});
});server.listen(3000);console.log("服务器启动成功!");server.on("connection", (connection)=>{console.log("有客户端连接");
});
客户端:CocosCreator界面实现
UI界面
NetModule.ts网络模块脚本
export default class GameNet{private static instance: GameNet = null;private ws: WebSocket = null;private constructor(){}public static getInstance(): GameNet{if(GameNet.instance === null){GameNet.instance = new GameNet();}return GameNet.instance;}public init(callback: Function, target: any){if(this.ws != null)return;this.ws = new WebSocket("ws://localhost:3000");this.ws.onopen = (event: Event)=>{callback.call(target, "登录成功");}this.ws.onmessage = (event: MessageEvent)=>{callback.call(target, event.data);}}public sendMsg(data: string){if(this.ws != null && this.ws.readyState != WebSocket.OPEN)return;this.ws.send(data);}
}
Helloworld.ts场景脚本
const {ccclass, property} = cc._decorator;import GameNet from "./NetModule"@ccclass
export default class Helloworld extends cc.Component {@property(cc.Button)btnLoad: cc.Button = null;@property(cc.Button)btnSend: cc.Button = null;@property(cc.EditBox)editBox: cc.EditBox = null;@property(cc.ScrollView)scrollViewMsg: cc.ScrollView = null;posY: number = 0;start () {this.btnLoad.node.on(cc.Node.EventType.TOUCH_END, this.dealLoad, this);this.btnSend.node.on(cc.Node.EventType.TOUCH_END, this.dealSendMsg, this);}private dealLoad(){GameNet.getInstance().init(this.showGetMsg, this);}private dealSendMsg(){let data:string = this.editBox.string;GameNet.getInstance().sendMsg(data);}private showGetMsg(data: string){let label: cc.Label = (new cc.Node()).addComponent(cc.Label);label.string = data;label.fontSize = 30;label.node.anchorX = 0;label.node.anchorY = 1;label.node.x = -this.scrollViewMsg.content.width*0.5 + 10;label.node.y = this.posY;this.scrollViewMsg.content.addChild(label.node);this.posY -= label.node.height;if(Math.abs(this.posY) > this.scrollViewMsg.content.height){this.scrollViewMsg.content.height = Math.abs(this.posY);this.scrollViewMsg.scrollToBottom();}//消息显示到聊天框上之后,清空输入框的内容this.editBox.string = "";}
}
使用命令行启动服务器:node WebsocketServer.js
运行两个客户端窗口起来。
效果图如下:
这篇关于CocosCreator Websocket简单使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!