首页是用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:8080this.#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>测试websocket</title></head><body></body><script type="module">//导入类import WebSocketClient from './websocketclient.js';//创建对象连接let a=new WebSocketClient('ws://localhost:8080');//向服务端发送信息a.sendWhenConnected('你好啊服务端');</script>
</html>
最后结果为这样