实现websocket的问题(Spring后端/Rect前端)



我正在尝试制作一个实时网络应用程序(一个虚拟多人棋盘游戏(。我从HTTPs请求开始,但现在我正尝试切换到websocket。我使用的是React前端和Spring Boot后端。我现在意识到我需要创建websocket,但我在实现它们时遇到了困难。

在react中使用标准的websocket对象对测试服务器(echo.websocket.org(很有效,但大多数在线指南似乎都建议使用STOMP端点。如果我在后台使用STOMP端点,我似乎无法使用通用的websocket对象。考虑到我想发送的数据是一个小数组(例如播放器的坐标(到连接到服务器的所有客户端,STOMP是正确的协议吗?或者我可以简化它吗?

前端反应组件的一部分。

import React from 'react';
import Stomp from 'stompjs';
componentDidMount() {
const ws = ("ws://localhost:8080/player");
var client = Stomp.client(ws);
client.connect({}, function() {
client.send("/location/update", {}, "coord: [3,2]");
});
}

后端的相关控制器。

@Controller
public class playerController {
public Player b = new Player("a", 1, 1, 1);
@MessageMapping("/player/location/update")
@SendTo("/playerLocation")
public int[] validClick(String value) throws Exception {
Thread.sleep(1000);
JSONObject temp = new JSONObject(value);
JSONArray val = temp.getJSONArray("coord");
int[] coord = {val.getInt(0), val.getInt(1)};
b.updateLocation(coord);
int[] newCoord = b.getLocation();
System.out.println(newCoord[0] + "," + newCoord[1]);
return b.getLocation();
}

配置文件:WebsocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/playerLocation");
config.setApplicationDestinationPrefixes("/api");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/player").withSockJS();
}

一切都编译得很好,但当在前端浏览器中查看网络开发工具时,websocket出现404错误,无法连接。这似乎表明后端是问题所在,但我不确定。欢迎提出任何建议。

最终我解决了这个问题,我们的websocket的格式实际上是正确的。问题是我们的文件结构不正确(所以webSocketConfig.java在错误的包中(,我们的Pom.xml也错误。我们对Spring websockets有依赖关系,而不是Spring Boot websockets,类似地,在重新排列文件结构时,我们在包安排中引入了错误。

我给任何遇到类似问题的人的建议是:独立地遵循这样的教程,了解正确的文件和包结构,然后尝试调整您的设置以匹配。

最新更新