2班的游戏

前端

https://gitee.com/yuanmatansuo/games-of-class-2.git

后端

https://gitee.com/yuanmatansuo/end-of-day-end.git

 

 

1班的游戏

前端

https://gitee.com/yuanmatansuo/class-1-game.git

后端

https://gitee.com/yuanmatansuo/escape-from-the-pentagon.git

 

 

WebSocket核心

 

<!--websocket 包 游戏多人连接核心包-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
	<version>3.4.4</version>
</dependency>
package com.xxgc.zde.config;

import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 启用简单的消息代理,客户端可以订阅以 /topic 开头的主题
        config.enableSimpleBroker("/topic");
        // 设置应用的目的地前缀,客户端发送消息时需要以 /app 开头
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册一个 WebSocket 端点,客户端可以通过 /ws 连接到 WebSocket 服务,允许所有来源的跨域请求,并使用 SockJS 作为备用方案
        registry.addEndpoint("/game").setAllowedOrigins("*").withSockJS();
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        // 为客户端入站通道添加一个拦截器
        registration.interceptors(new org.springframework.messaging.support.ChannelInterceptor() {
            @Override
            public org.springframework.messaging.Message<?> preSend(org.springframework.messaging.Message<?> message, org.springframework.messaging.MessageChannel channel) {
                // 获取消息的 Stomp 头访问器
                org.springframework.messaging.simp.stomp.StompHeaderAccessor accessor = org.springframework.messaging.simp.stomp.StompHeaderAccessor.wrap(message);
                // 检查消息的命令是否为 CONNECT,即客户端尝试连接时
                if (org.springframework.messaging.simp.stomp.StompCommand.CONNECT.equals(accessor.getCommand())) {
                    // 从请求头中获取名为 satoken 的 token
                    String token = accessor.getFirstNativeHeader("satoken");
                    if (token != null) {
                        // 设置 Sa - Token 的 token 值
                        StpUtil.setTokenValue(token);
                        // 检查用户是否已登录
                        if (StpUtil.isLogin()) {
                            // 如果已登录,允许消息继续传递
                            return message;
                        }
                    }
                    // 如果未登录或 token 无效,阻止消息传递
                    return null;
                }
                // 对于非 CONNECT 命令的消息,直接允许传递
                return message;
            }
        });
    }
}
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class ChatController {
    @MessageMapping("/chat")
    @SendTo("/topic/chat")
    public String handleMessage(String message) {
        // 处理客户端发送到 /app/chat 的消息,并将消息广播到 /topic/chat 主题
        return message;
    }
}

 

 

前端 

import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';

export default defineConfig({
    plugins: [uni()],
    server: {
        host: "localhost",
        port: 5173,
        proxy: {
            "/dev": {
                target: "http://192.168.1.16:8080",
                changeOrigin: true,
                rewrite: (path) => path.replace(/^\/dev/, ""),
                ws: true
            }
        }
    }
});    
//工程根路径 npm install stompjs
import Stomp from 'stompjs';

class ChatService {
    constructor(config) {
        this.config = config;
        this.stompClient = null;
        this.init();
    }

    init() {
        const socket = uni.connectSocket({
            url: this.config.url,
            header: {
                satoken: this.config.satoken
            },
            success: () => {
                console.log('WebSocket 连接成功');
                this.stompClient = Stomp.over(socket);
                this.stompClient.connect({}, () => {
                    console.log('STOMP 连接成功');
                });
            },
            fail: (err) => {
                console.error('WebSocket 连接失败', err);
            }
        });
    }

    subscribe(destination, callback) {
        if (this.stompClient) {
            this.stompClient.subscribe(destination, (message) => {
                callback(message.body);
            });
        }
    }

    sendMessage(destination, message) {
        if (this.stompClient) {
            this.stompClient.send(destination, {}, message);
        }
    }
}

export default ChatService;

 

//导入及时通讯插件
import ChatService from '@/utils/chatService.js';

 

initWebsocket(){
    this.chatService = new ChatService({
            url:"ws://192.168.1.16:8080/dev/game",
            satoken:uni.getStorageSync("token")
			})
    //订阅结果信息
    this.chatService.subscribe('/topic/chat',(message) =>{
            console.log("我收到订阅消息了",message);
			});
},
sendMessage(){
    this.chatService.sendMessage("/app/chat",this.message);
    this.message = "";
}

 

最后修改于 2025-04-11 10:07:00
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇