前言
在现代 Web 开发中,前端和后端的协作至关重要,特别是在需要实时交互和数据更新的应用场景中。WebSocket 技术作为一种全双工通信协议,使得前端和后端之间的实时数据传输变得更加高效和稳定。本文探讨如何设计和实现一个实时匹配系统,其中前端负责展示用户界面并与后端进行交互,而后端则通过 WebSocket 协议来处理数据通信。
前端状态管理
Vuex Store 配置
在 store/pk.js 中定义匹配相关状态:
import ModuleUser from './user'
export default {
state: {
socket: null, // ws 链接
opponent_username: "",
opponent_photo: "",
status: "matching", // matching 表示匹配界面,playing 表示对战界面
},
getters: {},
mutations: {
updateSocket(state, socket) { state.socket = socket; },
updateOpponent(state, opponent) {
state.opponent_username = opponent.username;
state.opponent_photo = opponent.photo;
},
updateStatus(state, status) { state.status = status; }
},
actions: {},
modules: { user: ModuleUser }
}
在 store/index.js 中引入模块:
import { createStore } from 'vuex'
import ModuleUser from './user'
import ModulePk from './pk'
export default createStore({
state: {},
getters: {},
mutations: {},
actions: {},
modules: { user: ModuleUser, pk: ModulePk }
})
建立 WebSocket 连接
在 views/pk/PKIndex.vue 中使用 Vue 3 Composition API 建立连接:
<template>
<PlayGround/>
</template>
<script>
import PlayGround from '@/components/PlayGround.vue'
import { onMounted, onUnmounted } from 'vue'
import { useStore } from 'vuex'
export default {
name: "PKindex",
components: { PlayGround },
setup() {
const store = useStore()
const socketUrl = `ws://127.0.0.1:3000/websocket/${store.state.user.id}/`
let socket = null
onMounted(() => {
socket = new WebSocket(socketUrl)
socket.onopen = () => {
console.log("connected!")
store.commit("updateSocket", socket)
}
socket.onmessage = msg => {
const data = JSON.parse(msg.data)
console.log(data)
}
socket.onclose = () => {
console.log("disconnected!")
}
})
onUnmounted(() => {
if (socket) socket.close()
})
}
}
</script>
<style scoped></style>
JWT 身份验证
若使用 userId 建立 ws 连接,用户可伪装成任意用户,因此不安全。应使用 token 进行验证。
修改连接 URL:
const socketUrl = `ws://127.0.0.1:3000/websocket/${store.state.user.token}/`;
后端添加 JWT 验证逻辑 consumer/utils/JwtAuthentication.java:
package org.example.backend.consumer.utils;
import io.jsonwebtoken.Claims;
import org.example.backend.utils.JwtUtil;
public class JwtAuthentication {
public static Integer getUserId(String token) {
int userId = -1;
try {
Claims claims = JwtUtil.parseJWT(token);
userId = Integer.parseInt(claims.getSubject());
} catch (Exception e) {
throw new RuntimeException(e);
}
return userId;
}
}
修改 consumer/WebSocketServer.java 的 onOpen 方法:
@OnOpen
public void onOpen(Session session, @PathParam("token") String token) throws IOException {
this.session = session;
System.out.println("connected to websocket");
Integer userId = JwtAuthentication.getUserId(token);
User user = userMapper.selectById(userId);
if (user != null) {
users.put(userId, this);
} else {
this.session.close();
}
}
匹配界面与对战界面切换
在 views/pk/PKindexView.vue 中根据状态渲染不同组件:
<template>
<PlayGround v-if="$store.state.pk.status === 'playing'"/>
<MatchGround v-if="$store.state.pk.status === 'matching'"/>
</template>
创建匹配页面组件 components/MatchGround.vue:
<template>
<div class="matchground">
<div class="row">
<div class="col-6">
<div class="user-photo"><img :src="$store.state.user.photo" alt=""></div>
<div class="user-username">{{ $store.state.user.username }}</div>
</div>
<div class="col-6">
<div class="user-photo"><img :src="$store.state.pk.opponent_photo" alt=""></div>
<div class="user-username">{{ $store.state.pk.opponent_username }}</div>
</div>
<div class="col-12" style="text-align: center; padding-top: 15vh;">
<button @click="click_match_btn" type="button" class="btn btn-warning btn-lg">{{ match_btn_info }}</button>
</div>
</div>
</div>
</template>
<script>
import { ref } from 'vue'
import { useStore } from 'vuex';
export default {
setup() {
const store = useStore();
let match_btn_info = ref("开始匹配");
const click_match_btn = () => {
if (match_btn_info.value === "开始匹配") {
match_btn_info.value = "取消";
store.state.pk.socket.send(JSON.stringify({ event: "start-matching", }));
} else {
match_btn_info.value = "开始匹配";
store.state.pk.socket.send(JSON.stringify({ event: "stop-matching", }));
}
}
return { match_btn_info, click_match_btn };
}
}
</script>
<style scoped>
div.matchground { width: 60vw; height: 70vh; margin: 40px auto; background-color: rgba(50,50,50,0.5); }
div.user-photo { text-align: center; padding-top: 10vh; }
div.user-photo>img { border-radius: 50%; width: 20vh; }
div.user-username { text-align: center; font-size: 24px; font-weight: 600; color: white; padding-top: 2vh; }
</style>

后端匹配逻辑
consumer/WebSocketServer.java 核心实现:
@Component
@ServerEndpoint("/websocket/{token}")
public class WebSocketServer {
private final static ConcurrentHashMap<Integer, WebSocketServer> users = new ConcurrentHashMap<>();
private final static CopyOnWriteArraySet<User> matchpool = new CopyOnWriteArraySet<>();
private User user;
private Session session = null;
private static UserMapper userMapper;
@Autowired
public void setUserMapper(UserMapper userMapper) {
WebSocketServer.userMapper = userMapper;
}
@OnOpen
public void onOpen(Session session, @PathParam("token") String token) throws IOException {
this.session = session;
Integer userId = JwtAuthentication.getUserId(token);
this.user = userMapper.selectById(userId);
if (this.user != null) {
users.put(userId, this);
} else {
this.session.close();
}
}
@OnClose
public void onClose() {
if (this.user != null) {
users.remove(this.user.getId());
matchpool.remove(this.user);
}
}
private void startMatching() {
matchpool.add(this.user);
while (matchpool.size() >= 2) {
Iterator<User> it = matchpool.iterator();
User a = it.next(), b = it.next();
matchpool.remove(a);
matchpool.remove(b);
Game game = new Game(13, 14, 20);
game.createMap();
JSONObject respA = new JSONObject();
respA.put("event", "start-matching");
respA.put("opponent_username", b.getUsername());
respA.put("opponent_photo", b.getPhoto());
respA.put("gamemap", game.getG());
users.get(a.getId()).sendMessage(respA.toJSONString());
JSONObject respB = new JSONObject();
respB.put("event", "start-matching");
respB.put("opponent_username", a.getUsername());
respB.put("opponent_photo", a.getPhoto());
respB.put("gamemap", game.getG());
users.get(b.getId()).sendMessage(respB.toJSONString());
}
}
private void stopMatching() {
matchpool.remove(this.user);
}
@OnMessage
public void onMessage(String message, Session session) {
JSONObject data = JSONObject.parseObject(message);
String event = data.getString("event");
if ("start-matching".equals(event)) {
startMatching();
} else if ("stop-matching".equals(event)) {
stopMatching();
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessage(String message) {
synchronized (this.session) {
try {
this.session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
前端接收消息并处理:
socket.onmessage = msg => {
const data = JSON.parse(msg.data);
if (data.event === "start-matching") {
store.commit("updateOpponent", {
username: data.opponent_username,
photo: data.opponent_photo,
});
setTimeout(() => {
store.commit("updateStatus", "playing");
}, 2000);
store.commit("updateGamemap", data.gamemap);
}
};
地图生成算法
后端创建 Game 类实现游戏流程,使用深度优先搜索(DFS)算法检查地图连通性。
consumer/utils/Game.java:
package org.example.backend.consumer.utils;
import java.util.Random;
public class Game {
private final Integer rows;
private final Integer cols;
private final Integer inner_walls_count;
private final int[][] g;
private final static int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
public Game(Integer rows, Integer cols, Integer inner_walls_count) {
this.rows = rows;
this.cols = cols;
this.inner_walls_count = inner_walls_count;
this.g = new int[rows][cols];
}
public int[][] getG() { return g; }
private boolean check_connectivity(int sx, int sy, int tx, int ty) {
if (sx == tx && sy == ty) return true;
g[sx][sy] = 1;
for (int i = 0; i < 4; i++) {
int x = sx + dx[i], y = sy + dy[i];
if (x >= 0 && x < this.rows && y >= 0 && y < this.cols && g[x][y] == 0) {
if (check_connectivity(x, y, tx, ty)) {
g[sx][sy] = 0;
return true;
}
}
}
g[sx][sy] = 0;
return false;
}
private boolean draw() {
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < this.cols; j++) {
g[i][j] = 0;
}
}
for (int r = 0; r < this.rows; r++) {
g[r][0] = g[r][this.cols - 1] = 1;
}
for (int c = 0; c < this.cols; c++) {
g[0][c] = g[this.rows - 1][c] = 1;
}
Random random = new Random();
for (int i = 0; i < this.inner_walls_count / 2; i++) {
for (int j = 0; j < 1000; j++) {
int r = random.nextInt(this.rows);
int c = random.nextInt(this.cols);
if (g[r][c] == 1 || g[this.rows - 1 - r][this.cols - 1 - c] == 1) continue;
if (r == this.rows - 2 && c == 1 || r == 1 && c == this.cols - 2) continue;
g[r][c] = g[this.rows - 1 - r][this.cols - 1 - c] = 1;
break;
}
}
return check_connectivity(this.rows - 2, 1, 1, this.cols - 2);
}
public void createMap() {
for (int i = 0; i < 1000; i++) {
if (draw()) break;
}
}
}
总结
本文介绍了如何使用 WebSocket 实现前端与后端的实时匹配。前端通过 Vuex 管理状态,动态渲染匹配或对战界面;后端利用 WebSocket Server 处理连接、验证及匹配池逻辑。双方通过事件驱动保持数据同步,确保实时交互体验。


