uni-app 使用WebSocket监听并响应

uni-app 使用WebSocket监听并响应

后端开放端口

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
    @Autowired
    private TokenProvider tokenProvider;

    public WebSocketConfiguration() {
    }

    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
	    //给uni-app使用SockJs时因为SockJs的问题导致使用出错,所以后端开放监听端口给uni-app时不要调用withSockJS()
    	//stompEndpointRegistry.addEndpoint(new String[]{"/endpointNotification-app"}).setAllowedOrigins(new String[]{"*"}).withSockJS();
        stompEndpointRegistry.addEndpoint(new String[]{"/endpointNotification-app"}).setAllowedOrigins("*");
    }

    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker(new String[]{"/user", "/topic"});
        registry.setApplicationDestinationPrefixes(new String[]{"/app"});
        registry.setUserDestinationPrefix("/user");
    }

    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor[]{new ChannelInterceptorAdapter() {
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor = (StompHeaderAccessor)MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                    String jwt = null;
                    String bearerToken = accessor.getFirstNativeHeader("Authorization");

                    try {
                        Base64 base64 = new Base64();
                        String decodeBearerToken = new String(base64.decode(bearerToken), "UTF-8");
                        if (StringUtils.hasText(decodeBearerToken) && decodeBearerToken.startsWith("Bearer ")) {
                            jwt = decodeBearerToken.substring(7, decodeBearerToken.length());
                        }

                        if (!StringUtils.hasText(jwt) || !WebSocketConfiguration.this.tokenProvider.validateToken(jwt)) {
                            throw new UserFriendlyException("禁止访问");
                        }

                        Authentication authentication = WebSocketConfiguration.this.tokenProvider.getAuthentication(jwt);
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    } catch (UnsupportedEncodingException var9) {
                        throw new UserFriendlyException("编码错误");
                    }
                }

                return message;
            }
        }});
    }
}

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

使用时

	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);
	},
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值