uni-app + SpringBoot +stomp 支持websocket 打包app

本文详细介绍了WebSocket在后端的配置,包括使用SpringBoot实现的WebSocketMessageBroker,以及如何在uni-app中使用WebSocket进行通信。重点讲解了如何在uni-app中正确设置URL和监听事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、概述:

websocket 协议是在http 协议的基础上的升级,通过一次http 请求建立长连接,转而变为TCP 的全双工通信;而http 协议是一问一答的请求方式方式。

二、配置:

1. 后端配置

@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

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. 使用

	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);
	},

### 使用Java和UniApp构建WebSocket聊天室 #### 后端部分:基于Spring BootWebSocket服务器配置 为了创建一个WebSocket聊天室,首先需要设置后端服务来处理客户端之间的通信。这里采用的是Spring Boot框架。 在`pom.xml`文件中加入依赖项以支持WebSocket: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 定义WebSocket配置类,用于注册处理器并指定允许跨域请求: ```java @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); // 广播路径前缀 config.setApplicationDestinationPrefixes("/app"); // 应用程序目的地前缀 } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS(); // 注册STOMP终端节点 } } ``` 编写控制器接收来自前端的消息并向所有已连接用户广播这些消息[^1]: ```java @Controller public class ChatController { @MessageMapping("/chat.sendMessage") // 接收消息映射 @SendTo("/topic/public") // 发送至订阅者 public ChatMessage sendMessage(ChatMessage chatMessage) throws Exception { return chatMessage; } static class ChatMessage { // 消息实体类 private String content; // getter and setter methods... // toString method... } } ``` #### 前端部分:利用UniApp开发聊天界面并与后端交互 对于移动端应用来说,可以借助于Vue.js的强大生态体系——特别是其子集NVUE(Native Vue),通过它能够快速搭建起具有原生性能的应用程序。下面是一个简单的例子展示怎样建立与上述后台系统的链接以及发送/接受数据的过程[^3]。 安装必要的npm包,在项目的根目录下执行命令行指令: ```bash npm install socket.io-client --save ``` 接着可以在页面组件里引入Socket.IO库,并初始化实例对象以便后续调用API方法来进行实时通讯操作: ```javascript import io from 'socket.io-client'; export default { data() { return { socket: null, messages: [], newMessage: '' }; }, onLoad() { this.socket = io('http://localhost:8080'); // 连接到本地运行的服务 this.socket.on('connect', () => console.log('Connected to server')); this.socket.on('message', (msg) => { this.messages.push(msg); }); }, methods: { sendMsg() { const msg = {content: this.newMessage}; this.socket.emit('sendMessage', JSON.stringify(msg)); this.newMessage = ''; } } } ``` 最后,记得调整HTML模板结构使其适应实际需求,比如显示历史记录列表、输入框等UI元素;同时也要考虑异常情况下的错误提示逻辑设计等问题[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值