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();
},
method:{
initWebSocket(){
let userId = 1;
let wsUrl = 'ws://127.0.0.1:8080/webSocketServer/'+ userId +'';
this.websock = new WebSocket(wsUrl);
this.websock.onopen= this.webSocketOnopen();
this.websock.onmessage = this.webSocketOnmessage;
this.websock.onerror = this.webSockeToOnerror;
this.websock.onclose = this.webSocketClose;
},
webSocketOnopen(){
this.webSocketsEnd();
},
webSocketsEnd(){
let actions = {'test','测试链接socket'};
this.websock.send(JSON.stringify(actions));
},
webSocketOnmessage(data){
console.log(data);
},
websocketonerror(){
setTimeout(()=>{
this.initWebSocket();
},10000)
},
websocketclose(data){
console.log('socket断开连接',data);
},
},
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();
},
method:{
initWebSocket(){
let userId = 1;
let socketURL = process.env.VUE_APP_BASE_API;
let wsUrl = `ws://`+ location.host + socketURL +`/webSocketServer/`+userid+``;
this.websock = new WebSocket(wsUrl);
this.websock.onopen= this.webSocketOnopen();
this.websock.onmessage = this.webSocketOnmessage;
this.websock.onerror = this.webSockeToOnerror;
this.websock.onclose = this.webSocketClose;
},
webSocketOnopen(){
this.webSocketsEnd();
},
webSocketsEnd(){
let actions = {'test','测试链接socket'};
this.websock.send(JSON.stringify(actions));
},
webSocketOnmessage(data){
console.log(data);
},
websocketonerror(){
setTimeout(()=>{
this.initWebSocket();
},10000)
},
websocketclose(data){
console.log('socket断开连接',data);
},
},
destroyed() {
this.websock.close();
},
}
</script>