文章目录
一、概述:
websocket 协议是在http 协议的基础上的升级,通过一次http 请求建立长连接,转而变为TCP 的全双工通信;而http 协议是一问一答的请求方式方式。
二、配置:
1. 后端配置
java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {//注册STOMP协议的节点(endpoint),并映射指定的url
//注册一个STOMP的endpoint,并指定使用SockJS协议
// 此处配置支持PC 端浏览器,客户端访问采用http
registry.addEndpoint("/websocket")
.setAllowedOriginPatterns("*")
.withSockJS();
// 此处配置支持uniapp app 端打包,不要带withSockJS, 客户端访问 采用ws 协议
registry.addEndpoint("/websocket-app").setAllowedOriginPatterns("*");
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {//配置消息代理(Message Broker)
//广播式应配置一个/topic消息代理
registry.enableSimpleBroker("/topic");
}
}
2. uni-app(app端)
websocket-uni.js
java
let socketOpen = false;
let socketMsgQueue = [];
import http from "@/common/Http.vue";
export default {
client: null,
baseURL: `ws://192.168.1.1:9109/websocket-app`,//uni-app使用时不能使用http不然监听不到,需要使用ws
init(headers) {
if (this.client) {
return Promise.resolve(this.client);
}
return new Promise((resolve, reject) => {
const ws = {
send: this.sendMessage,
onopen: null,
onmessage: null,
close: this.closeSocket,
};
uni.connectSocket({
url: this.baseURL,
header: headers,
success: function() {
console.log("WebSocket连接成功");
}
});
uni.onSocketOpen(function(res) {
console.log('WebSocket连接已打开!', res);
socketOpen = true;
for (let i = 0; i < socketMsgQueue.length; i++) {
ws.send(socketMsgQueue[i]);
}
socketMsgQueue = [];
ws.onopen && ws.onopen();
});
uni.onSocketMessage(function(res) {
console.log("回馈")
ws.onmessage && ws.onmessage(res);
});
uni.onSocketError(function(res) {
console.log('WebSocket 错误!', res);
});
uni.onSocketClose((res) => {
this.client.disconnect();
this.client = null;
socketOpen = false;
console.log('WebSocket 已关闭!', res);
});
const Stomp = require('./stomp.js').Stomp;
Stomp.setInterval = function(interval, f) {
return setInterval(f, interval);
};
Stomp.clearInterval = function(id) {
return clearInterval(id);
};
const client = this.client = Stomp.over(ws);
client.connect(headers, function() {
console.log('stomp connected');
resolve(client);
});
});
},
disconnect() {
uni.closeSocket();
},
sendMessage(message) {
if (socketOpen) {
uni.sendSocketMessage({
data: message,
});
} else {
socketMsgQueue.push(message);
}
},
closeSocket() {
console.log('closeSocket');
},
};
3. 使用
java
import WebSocket from '@/components/js/websocket-uni1.js';
if (self.map.get("token")) {//需要上传token
headers.Authorization = self.map.get("token");
}
WebSocket.init(headers).then(client => {
//接收反馈端口,成功方法,错误方法
client.subscribe('/topic/getResponse', this.responseCallback, this.onFailed);
});
responseCallback: function(frame) {
let self=this;
let body = JSON.parse(frame.body);
uni.showToast({
icon:"success",
icon: 'none',
position:"center",
title:"消息:您有一个新的消息,请注意接收"
},2000)
},
onFailed: function(frame) {
//this.$notify.error({
// title: '系统错误',
// message: '消息服务连接失败!',
//});
console.log('STOMP: ' + frame);
},