参考连接:
[websocket](websocketDemo · essay-note (zq99299.github.io))
链接第12节简述了从websocket到sockjs到stomp
代码示例
websocket
不需要安装任何插件 直接 new webSocket即可
let ws = new WebSocket('ws://localhost:8080/myHandler')
ws.onopen = () => {
this.msg = '链接成功.'
// Web Socket 已连接上,使用 send() 方法发送数据
ws.send('发送数据')
}
ws.onmessage = (evt) => {
let receivedMsg = evt.data
this.msg = '数据已接收...:' + receivedMsg
}
ws.onclose = () => {
// 关闭 websocket
this.msg = '连接已关闭...'
}
sockJs stomp
vue 安装
npm install stompjs
npm install sockjs-client
最好也安装 npm install websocket 因为自身实践,不安装会报错
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
export default {
data () {
return {
status: '未链接'
}
},
mounted () {
// 注意这里的地址,和之前的不是一个项目了
var ws = new SockJS('http://localhost:8082/stomp')
var stomp = Stomp.over(ws)
// 注意这里的header 暂时不是必须的。
var headers = {
login: 'mylogin',
passcode: 'mypasscode',
// additional header
'client-id': 'my-client-id'
}
stomp .connect(headers,
() => {
this.status = '已链接'
//连接成功 可以进行订阅消息
stomp.subscribe('/topic/public_news', message => {
let news = JSON.parse(message.body)
// 把获取到的列表赋值给该变量,页面中会循环出该信息
this.publicNews = news
})
},
(error) => {
this.status = '链接失败:' + error
})
}
}
// 断开链接
disconnect () {
stomp .disconnect()
this.msg.info = `链接断开: 手动断开`
}
扩展 vue项目 websocket nginx 代理
创建websocket连接
let scoketUrl=`ws:${location.host}/socket/stomp`
let ws=new WebSocket(socketUrl)
this.stomp=Stomp.over(ws);
this.stomp.connect(header,()=>{
this.stomp.subscribe("/你的请求路径",message=>{
let move= JSON.parse(message.body)
})
console.log("链接成功")
},error=>{
console.log("链接失败")
})
vue.config.js 配置websocket跨域
//proxy
"/socket":{
//要访问的跨域域名
target:'http://你的后台ip:端口',
changOrigin:true,//开启代理
ws:true,
pathRewrite:{
' ^/socket':' '
}
}
nginx 配置conf
不同于http
location/socket/ {
proxy_pass http://后台访问地址/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 36000s; #1小时未传输数据则关闭接
}
网友评论