vue3使用WebSocket

const wsUrl = ref('xxxxxxxx');//链接地址
const initWebSocket = () => {//初始化
  websock.value = new WebSocket(wsUrl.value);
  websock.value.onopen = () => {
    console.log("连接成功");
  };
  websock.value.onmessage = (e) => {
    console.log(JSON.parse(e.data), "--广播返回的消息");
  };
  websock.value.onerror = () => {
    console.log("连接错误");
  };
};
//发送消息
const sendMessage = (msg) => {
  console.log(msg, "0");
  websock.value.send(msg);
};
//关闭链接(在页面销毁时可销毁链接)
const closeWebSocket = () => {
  websock.value.close();
};

  

posted @ 2022-06-06 16:45  小万子呀  阅读(3031)  评论(0编辑  收藏  举报