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
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于使用 uni-app 实现通过 WebSocket 给对方发送请求的问题,你可以按照以下步骤进行操作: 1. 首先,确保你的 uni-app 项目已经安装了 `uni-socket.io` 插件。可以通过命令 `npm install uni-socket.io` 进行安装。 2. 在需要使用 WebSocket 的页面或组件中,引入 `uni-socket.io` 并创建一个 WebSocket 实例,例如: ```javascript import io from 'uni-socket.io'; // 创建 WebSocket 实例 const socket = io('ws://your_socket_server_address'); ``` 3. 在需要发送请求的地方,通过 `socket` 实例发送请求,例如: ```javascript // 发送请求 socket.emit('request', { data: 'your_data' }, (response) => { // 处理响应 console.log(response); }); ``` 这里的 `emit` 方法用于发送请求,第一个参数是请求的事件名,可以根据你的业务需求自定义。第二个参数是请求的数据,可以是一个对象。第三个参数是一个回调函数,用于处理服务器返回的响应。 4. 在服务端接收到请求后,进行相应的处理,并发送响应,例如: ```javascript // 监听请求事件 socket.on('request', (data, callback) => { // 处理请求 console.log(data); // 发送响应 callback('your_response_data'); }); ``` 这里的 `on` 方法用于监听客户端发送的请求,第一个参数是请求的事件名,需要与客户端发送请求时的事件名相对应。第二个参数是一个回调函数,用于处理客户端发送的请求,并发送响应。 以上就是通过 uni-app 使用 WebSocket 给对方发送请求的基本步骤。你可以根据具体的业务需求进行相应的调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值