VUE的websocket通讯

这个是在已经创建好的vue项目中进行一个加入了websocket

websocket语法

url是请求的地址
WebSocket(url[, protocols])
Socket.readyState
只读属性 readyState 表示连接状态,可以是以下值:

0 - 表示连接尚未建立。

1 - 表示连接已建立,可以进行通信。

2 - 表示连接正在进行关闭。

3 - 表示连接已经关闭或者连接不能打开。
Socket.bufferedAmount
只读属性 bufferedAmount 已被 send() 放入正在队列中等待传输,但是还没有发出的 UTF-8 文本字节数。
事件 事件处理程序 描述
open Socket.onopen 连接建立时触发
message Socket.onmessage 客户端接收服务端数据时触发
error Socket.onerror 通信发生错误时触发
close Socket.onclose 连接关闭时触发
方法 描述
Socket.send()
使用连接发送数据

Socket.close()
关闭连接

script的部分

  data() {
    return {
      value: "", //输入框的值
      path: "ws://192.168.1.22:18308/test", //后端的接口
      socket: "",
      websocketMessage: {},//接收的message返回来的值
    };
  },

生命周期函数部分

  created() {
    //进入聊天组件实例化websocket
    this.websocket_Init();
  },
  destroyed() {
    //组件卸载时,关闭websocket
    this.socket.close();
  },

methods部分

  methods: {
	    /**
	     * 实例化websocket
	     * @param {null}
	     * @returns {null}
	     */
	    websocket_Init() {
	      // 实例化socket
	      this.socket = new WebSocket(this.path);
	      // 监听socket连接
	      this.socket.onopen = this.open;
	      // 监听socket错误信息
	      this.socket.onerror = this.error;
	      //监听scket消息
	      this.socket.onmessage = this.getMessage;
	      //关闭socket
	      this.socket.onclose = this.socketClose;
	    },
	     /**
	     * 关闭连接
	     * @param {null}
	     * @returns {null}
	     */
	    socketClose(e) {
	      console.log("断开连接", e);
	    },
	
	    /**
	     * 连接socket
	     * @param {null}
	     * @returns {null}
	     */
	    open() {
	      console.log("socket连接成功");
	    },
	    /**
	     * 连接报错
	     * @param {null}
	     * @returns {str}
	     */
	    error(e) {
	      console.log("连接错误", e);
	    },
	    /**
	     * 接收消息
	     * @param {path}
	     * @returns {path}
	     */
	    getMessage(msg) {
	      console.log(msg);
	      this.websocketMessage = msg;
	    },
	    /**
	     * 发送消息
	     * @param {str}
	     * @returns {str}
	     */
	    sendvalue(value) {
	      console.log("send发送的" + value);
	      this.socket.send(value);
	    },
	        /**
	     * 点击回车事件
	     * @param {null}
	     * @return {void}
	     */
	    handleEnterThing() {
	      this.sendvalue(JSON.stringify(this.value)); //将输入的value转化为字符串
	    }
      },
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值