ws-common-util
v1.0.2
Published
封装的一个websocket简便工具类
Downloads
8
Readme
使用文档
下载
npm install ws-common-utilimport WsUtils from "ws-common-util"使用
// 创建 WebSocket 管理器实例
const wsManager = new WsUtils('ws://example.com/socket', (message) => {
console.log('收到消息:', message);
}, (error) => {
console.error('发生错误:', error);
});
// 建立 WebSocket 连接
wsManager.connect();
// 发送消息
wsManager.sendWebSocketMessage('Hello World');
// 定时检查连接状态并发送消息
wsManager.checkConnection({ action: 'ping' }, 5000);
// 关闭连接
wsManager.close();
实际使用
<script>
import webSocketManager from "ws-common-util";
export default {
name: 'App',
data() {
return {
socketConfig: {
socket: null,
host: "wss://127.0.0.1:xxxx/",
},
}
},
methods: {
initWebSocket() {
const that = this;
this.socketConfig.socket = new webSocketManager(that.socketConfig.host, that.handleMessage);
this.socketConfig.socket.checkConnection({
"test":0
})
},
handleMessage(msg) {
//...接收消息
},
},
created() {
this.initWebSocket()
},
beforeDestroy() {
this.socketConfig.socket.close()
}
}
</script>