【发布时间】:2019-04-19 20:23:15
【问题描述】:
我正在尝试制作一个实时网络应用程序(虚拟多人棋盘游戏)。我从 HTTPs 请求开始,但我现在正试图切换到 websockets。我正在使用 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 错误无法连接。这似乎表明后端是问题所在,但我不确定。任何建议表示赞赏。
【问题讨论】:
-
您为应用程序添加前缀“/api”,但我没有看到您在其他任何地方使用该前缀。
-
@Seraph 我尝试在 ws (localhost:8080/api/player) 和 client.send (/api/location/update) 中插入 /api,但仍然是 404。你会在哪里建议?
标签: reactjs spring-boot websocket