websocket封装
时间: 2023-08-31 19:05:14 浏览: 42
WebSocket是一种基于TCP协议的双向通信协议,它可以在浏览器和服务器之间建立实时的、双向的通信通道,可以用于实现实时聊天、在线游戏、数据推送等功能。在使用WebSocket时,我们需要进行一些封装,以便更方便地使用。
以下是一个简单的WebSocket封装示例:
```javascript
class WebSocketClient {
constructor(url) {
this.url = url;
this.socket = null;
this.callbacks = {};
this.connect();
}
connect() {
this.socket = new WebSocket(this.url);
this.socket.onopen = event => this.onOpen(event);
this.socket.onmessage = event => this.onMessage(event);
this.socket.onclose = event => this.onClose(event);
this.socket.onerror = event => this.onError(event);
}
onOpen(event) {
console.log('WebSocket连接成功!');
}
onMessage(event) {
const data = JSON.parse(event.data);
const callback = this.callbacks[data.type];
if (callback) {
callback(data);
}
}
onClose(event) {
console.log('WebSocket连接关闭!');
this.connect();
}
onError(event) {
console.error('WebSocket连接出错!');
}
send(type, data) {
this.socket.send(JSON.stringify({ type, data }));
}
on(type, callback) {
this.callbacks[type] = callback;
}
off(type) {
delete this.callbacks[type];
}
}
```
在这个封装中,我们使用了ES6的类来定义WebSocketClient对象,它接受一个url参数,在构造函数中建立WebSocket连接。我们定义了四个事件处理函数,分别是onOpen、onMessage、onClose和onError,用于处理WebSocket连接的打开、消息接收、关闭和错误事件。我们还定义了send、on和off三个方法,用于发送消息、绑定事件和解除事件绑定。
在使用WebSocketClient时,我们可以通过实例化一个WebSocketClient对象来建立WebSocket连接,并使用send、on和off方法来发送消息、绑定事件和解除事件绑定,示例代码如下:
```javascript
const socket = new WebSocketClient('ws://localhost:3000');
socket.send('message', { content: 'Hello, World!' });
socket.on('message', data => console.log(data));
socket.off('message');
```
以上是一个简单的WebSocket封装示例,具体实现可以根据需要进行修改和扩展。