目录
封装调用ws协议接口工具函数
页面调用
封装调用ws协议接口工具函数
- params:请求参数
- cb:服务器请求成功返回数据的回调函数
function createWs(params, cb) {const ws = new WebSocket("ws://124.222.224.186:8800");let timer = null;// 服务器连接成功处理函数ws.onopen = function () {// 连接成功后,调用发送参数的函数sendMessage();console.log("ws连接成功......");}// 服务器连接失败处理函数ws.onerror = function(err) {console.log("ws连接失败......", err);}// 断开服务器连接处理函数ws.onclose = function() {console.log("ws断开连接......");}// 请求成功后返回的数据处理函数ws.onmessage = function (res) {cb(res.data);}// 向ws发送参数function sendMessage() {if(ws.readyState === WebSocket.OPEN) {ws.send(params)}}}
页面调用
createWs("测试数据", (res) => {
console.log("111",res);
})