websocket的使用及nginx通信的ws代理配置

websocket的使用及nginx通信的ws代理配置

  • 最近在做的vue项目要使用websocket,本文讲述了websocket在vue中使用及打包后使用nginx代理。
    1、创建vue项目,这里不在详细去说,如果在创建项目时有疑问请访问: vue创建项目.
<template>
	<div></div>
</template>

<script>
	export default {
		name: 'socket',
		data(){
			return {
				websock: null,
			}
		},
		create(){
			this.initWebSocket(); // 初始化websocket
		},
		method:{
			// 初始化websocket
			initWebSocket(){
				let userId = 1;
				let wsUrl = 'ws://127.0.0.1:8080/webSocketServer/'+ userId +'';
				this.websock = new WebSocket(wsUrl); // 建立websocket
				this.websock.onopen= this.webSocketOnopen(); // 建立连接
				this.websock.onmessage = this.webSocketOnmessage; // 接受数据
      			this.websock.onerror = this.webSockeToOnerror; // 连接失败后重新连接
      			this.websock.onclose = this.webSocketClose; // 关闭socket
			},
			// 建立链接
			webSocketOnopen(){
				this.webSocketsEnd();
			},
			// 发送数据
			webSocketsEnd(){
				let actions = {'test','测试链接socket'};
				this.websock.send(JSON.stringify(actions));
			},
			// 接收后端返回的数据
			webSocketOnmessage(data){
				console.log(data);
			},
			// 建立链接失败后重连
			websocketonerror(){
				// 使用setTimeout是为了避免重新链接过快导致浏览器卡死
		        setTimeout(()=>{
		            this.initWebSocket();
		        },10000)
		    },
		    // 关闭连接
		    websocketclose(data){
		      	console.log('socket断开连接',data);
		    },
		}// 离开当前路由后销毁socket连接
		destroyed() {
		   this.websock.close();
		},
	}
</script>

  • 到目前为止,我们已经创建好了webSocket了,但是在打包后实际应用中,难免会遇到很多问题,这里我们选择了nginx代理方式进行演示。

1、配置nginx,打开nginx.conf

	server {
		listen			89;
		server_name		localhost;

		location / {
			root	iot/dist;
			index	index.html;
			try_files $uri $uri/ /index.html;
		}
		
		location /api {
            proxy_pass http://127.0.0.1:8080;
			# 开启nginx对websocket的支持
			proxy_http_version 1.1;
			proxy_set_header Upgrade $http_upgrade;
			proxy_set_header Connection "upgrade";
        }

	}

2、进入到vue全局配置.env下,如果没有.env,请在package.json同级目录下创建。

	# 配置socket使用地址
	VUE_APP_BASE_API = /api

3、其次进入到vue组件中进行修改,具体如下:

<template>
	<div></div>
</template>

<script>
	export default {
		name: 'socket',
		data(){
			return {
				websock: null,
			}
		},
		create(){
			this.initWebSocket(); // 初始化websocket
		},
		method:{
			// 初始化websocket
			initWebSocket(){
				let userId = 1;
				let socketURL = process.env.VUE_APP_BASE_API; // 获取vue全局配置env的变量
				let wsUrl = `ws://`+ location.host + socketURL +`/webSocketServer/`+userid+``;
				this.websock = new WebSocket(wsUrl); // 建立websocket
				this.websock.onopen= this.webSocketOnopen(); // 建立连接
				this.websock.onmessage = this.webSocketOnmessage; // 接受数据
      			this.websock.onerror = this.webSockeToOnerror; // 连接失败后重新连接
      			this.websock.onclose = this.webSocketClose; // 关闭socket
			},
			// 建立链接
			webSocketOnopen(){
				this.webSocketsEnd();
			},
			// 发送数据
			webSocketsEnd(){
				let actions = {'test','测试链接socket'};
				this.websock.send(JSON.stringify(actions));
			},
			// 接收后端返回的数据
			webSocketOnmessage(data){
				console.log(data);
			},
			// 建立链接失败后重连
			websocketonerror(){
				// 使用setTimeout是为了避免重新链接过快导致浏览器卡死
		        setTimeout(()=>{
		            this.initWebSocket();
		        },10000)
		    },
		    // 关闭连接
		    websocketclose(data){
		      	console.log('socket断开连接',data);
		    },
		}// 离开当前路由后销毁socket连接
		destroyed() {
		   this.websock.close();
		},
	}
</script>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值