vue项目中使用websocket

一、前言:

WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议,在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

二、在vue项目中使用websocket

1、模板部分

    <div></div>
</template>

2、js部分

<script>
    export default {
        data() {
            return {
                websock: null,//定义websock对象
            }
        },
    created(){
           //页面刚进入时开启长连接
            this.initWebSocket()
       },
    destroyed: function() {
    //页面销毁时关闭长连接
      this.websocketclose();
    },
    methods: { 
    	  //1、初始化weosocket 
      initWebSocket(){ 
       	try{
       		if(typeof(WebSocket) === "undefined"){ alert("您的浏览器不支持socket"); }
       		
					if(typeof MozWebSocket === 'function'){ WebSocket = MozWebSocket; }
					
					if(this.websock && this.websock.reayState === 1){ this.websock.close(); }
					
					const wsuri = process.env.WS_API + "/websocket/threadsocket";//ws地址
					
        		this.websock = new WebSocket(wsuri); 
        		
        		this.websocket.onopen = this.websocketonopen;//打开连接

        		this.websocket.onerror = this.websocketonerror;//连接失败

        		this.websock.onmessage = this.websocketonmessage; //发送数据

        		this.websock.onclose = this.websocketclose;//关闭连接
        		
				}catch(err){
				
					console.log(err);
					
				}
       }, 
       
		  //1、打开连接
      websocketonopen(e) {
        console.log("WebSocket连接成功");
      },
		  //2、连接失败
      websocketonerror(e) { //连接发生错误错误
        console.log("WebSocket连接发生错误");
      },
		  //3、接收后台的响应数据
      websocketonmessage(e){ //数据接收 
       const data = JSON.parse(e.data);
       console.log(data); 
      }, 
		  //4、发送数据
      websocketsend(message){//数据发送 
       this.websock.send(message); 
      }, 
		  //5、关闭连接 
      websocketclose(e){
       console.log("connection closed (" + e.code + ")"); 
     }
   }, 
  }
 </script>
 

三、注意:如果是原生js中使用websocket

let websock = null;
if ('WebSocket' in window) {
       websocket = new WebSocket("ws://192.168.1.99:8080/tv/websocket");
   } else{
	alert("当前浏览器不支持websock")
}

//1、打开连接
websock.onopen = function(){}

//2、连接失败
websock.onerror = function(){}

//3、接收后台的响应数据
websock.onmessage = function(e){console.log(JSON.parse(e.data))}

//4、发送数据
let message = {id:1};
this.websock.send(message);

//5、监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {?
	websocket.close();?//关闭WebSocket连接 
};
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值