【问题标题】:Issues implementing websockets (Spring backend/React frontend)实现 websocket 的问题(Spring 后端/React 前端)
【发布时间】: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


【解决方案1】:

最后我解决了问题,我们的 websockets 的格式实际上是正确的。问题是我们的文件结构不正确(所以 webSocketConfig.java 在错误的包中)并且我们的 Pom.xml 是错误的。我们依赖于 Spring websockets 而不是 Spring Boot websockets,同样在重新排列文件结构时,我们在包排列中引入了错误。

我对任何遇到类似问题的人的建议:按照教程 such as this independently 了解正确的文件和包结构,然后尝试调整您的设置以匹配。

【讨论】:

    猜你喜欢
    • 2017-09-06
    • 2022-06-30
    • 2019-09-24
    • 2021-04-28
    • 2021-05-29
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    相关资源
    最近更新 更多