vue+node 建立webSocket 连接

首先发几个参考文档

 

WebSocket 教程--阮一峰

WebSocket其实没那么难

Vue中使用websocket的正确使用方法

webSocket 简介
 

首先,WebSocket是一种通信协议,区别于HTTP协议,HTTP协议只能实现客户端请求,服务端响应的这种单项通信。
而WebSocket可以实现客户端与服务端的双向通讯,说白了,最大也是最明显的区别就是可以做到服务端主动将消息推送给客户端。


其余的特点有:

  • 握手阶段采用 HTTP 协议。
  • 数据格式轻量,性能开销小。客户端与服务端进行数据交换时,服务端到客户端的数据包头只有2到10字节,客户端到服务端需要加上另外4字节的掩码。HTTP每次都需要携带完整头部。
  • 更好的二进制支持,可以发送文本,和二进制数据
  • 没有同源限制,客户端可以与任意服务器通信
  • 协议标识符是ws(如果加密,则是wss),请求的地址就是后端支持websocket的API。

webSocke 创建实例

服务端:首先在node服务端,首先需要使用如下语句安装拓展

 cnpm  install  express  express-ws -S

 客户端创建webSocket请求连接

<template>
  <div class="websocket">
    <textarea cols="50" rows="20" v-model="requireData"></textarea>
    <el-button type="primary" @click="connectWebScket">连接到服务器webSocket</el-button>
    <el-button type="danger" @click="closeConnect">关闭连接</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      websock: null, //用于初始化为一个webSocket实例
      requireData: "接收到服务端发送的数据:" //用于接收服务器返回的数据
    };
  },
  destroyed() {
    //销毁组件,跳转路由时关闭webSocket连接
    this.websock.close();
  },
  methods: {
    //连接到webSocket
    connectWebScket() {
      this.initWebSocket();
    },
    //关闭连接
    closeConnect() {
      this.websock.close();
    },
    initWebSocket() {
      //初始化weosocket
      // 以    ws://服务器地址/webSocket  路由的形式建立连接
      const wsuri = "ws://127.0.0.1:8081/test";
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    //连接建立之后执行send方法发送数据
    websocketonopen() {
      let actions = {
        sendCustomData: "建立连接后,客户端自动发送数据****到服务端"
      };
      this.websocketsend(actions);
    },
    //连接建立失败重连
    websocketonerror() {
      this.initWebSocket();
    },
    //接收服务端数据
    websocketonmessage(e) {
      const redata = e.data;
      this.requireData = this.requireData + "\n" + redata;
      console.log("接收到服务端发送的数据:", redata);
    },
    //客户端发送数据
    websocketsend(Data) {
      this.websock.send(Data);
    },
    //关闭webSocket连接
    websocketclose(e) {
      console.log("关闭webSocket连接:", e);
    }
  }
};
</script>

<style scoped>
</style>

效果图:

 

 

 

 

 

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值