nodejs创建ws服务器,前端浏览器用websocket接收信息和发送信息给服务端

首页是用nodejs建立服务器端
//wsserver.js

const WebSocket=require('ws');
const wss=new WebSocket.Server({port:8080});
wss.on('connection',function connection(ws){
    ws.on('error',console.error);
    //接收客户端发送过来的信息
    ws.on('message',function message(data){
        console.log('received:%s',data);
    });
    //向服务端发送信息
    ws.send('你好啊客户端');
})

//创建前端的websocket文件
websocketclient.js

class WebSocketClient {
	//私有成员url和socket变量
    #privateUrl = '';
    #privateSocket = null;
    #messageQueue = []; // 消息队列,用于存储在连接打开前的消息

    constructor(url) {
        this.#privateUrl = url;
        //创建websocket对象,url就是服务器地址:ws://localhost:8080
        this.#privateSocket = new WebSocket(this.#privateUrl);
        //建立连接函数
        this.#setupWebSocketEvents();
    }

    #setupWebSocketEvents() {
        this.#privateSocket.onopen = () => {
            console.log(`连接成功,等待服务端数据推送[onopen]...`);
            // 连接打开后,发送队列中的消息
            this.#messageQueue.forEach(msg => this.#privateSocket.send(msg));
            this.#messageQueue = []; // 清空消息队列
        };
        //下面三个必须用箭头函数才能反应上下文关系
        this.#privateSocket.onmessage = (event) => {
            console.log('服务端发送来的数据%s', event.data);
        };
        this.#privateSocket.onclose = () => {
            console.log('连接已断开[onclose]...');
        };
        this.#privateSocket.onerror = (event) => {
            console.log('连接异常[onerror]');
        };
    }

//这里客户端发送信息,如果是已经连接状态则直接发送信息,如果未打开连接或连接中,则把信息添加到队列中
    sendWhenConnected(message) {
        if (this.#privateSocket && this.#privateSocket.readyState === WebSocket.OPEN) {
            this.#privateSocket.send(message);
        } else {
            // 如果WebSocket尚未打开连接,则将消息添加到队列
            this.#messageQueue.push(message);
        }
    }

    
//关闭连接
    close() {
        if (this.#privateSocket) {
            this.#privateSocket.close();
            this.#privateSocket = null;
        }
    }
}
//导出WebSocketClient类
export default WebSocketClient;

//html文件,index.html

<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
        <title>测试websockettitle>
    head>
    <body>
        
    body>
    <script type="module">
    //导入类
        import WebSocketClient from './websocketclient.js';
        //创建对象连接
        let a=new WebSocketClient('ws://localhost:8080');
        //向服务端发送信息
        a.sendWhenConnected('你好啊服务端');
        
        
    script>
html>

最后结果为这样
nodejs创建ws服务器,前端浏览器用websocket接收信息和发送信息给服务端_第1张图片

你可能感兴趣的:(nodejs,服务器,前端,websocket)