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

运行两个客户端窗口起来。

效果图如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值