JS — websocket封装
class WebSocketRequest { constructor(url, options = {}) { this.url = url; this.socket = null; this.requestId = 0; this.requests = {}; this.options = Object.assign({}, options); this.connect(); } connect() { this.socket = new WebSocket(this.url); this.socket.addEventListener('open', () => { console.log(`WebSocket connected to ${this.url}`); if (this.options.onOpen) { this.options.onOpen(); } }); this.socket.addEventListener('close', (event) => { console.log(`WebSocket closed with code ${event.code}`); if (this.options.onClose) { this.options.onClose(event); } }); this.socket.addEventListener('error', (event) => { console.error('WebSocket error:', event); if (this.options.onError) { this.options.onError(event); } }); this.socket.addEventListener('message', (event) => { const response = JSON.parse(event.data); if (response.id && this.requests[response.id]) { this.requests[response.id](response.data); delete this.requests[response.id]; } }); } sendRequest(data, callback) { this.requestId++; this.requests[this.requestId] = callback; const request = { id: this.requestId, data: data, }; this.socket.send(JSON.stringify(request)); } close() { this.socket.close(); } }
//我们向WebSocketRequest
构造函数中传递了一个可选的options
对象,其中包含了可选的事件处理程序。这样,我们可以在WebSocket
实例发生打开、关闭、错误和接收消息等事件时,触发相应的处理程序。
//同时,我们添加了 close
方法来关闭 WebSocket 连接。这将在应用程序退出或需要断开连接时非常有用。
//在使用时,你可以选择传递任意数量的处理程序到options
对象中,以便监听各种事件。你还可以在构造函数中调用connect
方法,以便在初始化时自动连接 WebSocket。
const url = 'ws://your-websocket-server-url'; const socketRequest = new WebSocketRequest(url, { onOpen: () => { console.log('WebSocket opened'); }, onClose: (event) => { console.log(`WebSocket closed with code ${event.code}`); }, onError: (event) => { console.error('WebSocket error:', event); }, }); // 发送请求 const requestData = { message: 'Hello, server!' }; socketRequest.sendRequest(requestData, (response) => { console.log('Response:', response); }); // 关闭 WebSocket 连接 socketRequest.close();