实施websocket的问题(Spring后端/ React前端)

时间:2018-11-16 15:57:19

标签: reactjs spring-boot websocket

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

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

前端中的一部分React组件。

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错误,无法连接。这似乎表明后端是问题所在,但我不确定。任何建议表示赞赏。

1 个答案:

答案 0 :(得分:0)

最后,我解决了这个问题,我们的WebSocket的格式实际上是正确的。问题是我们的文件结构不正确(因此webSocketConfig.java位于错误的程序包中),而我们的Pom.xml错误。我们对Spring Websockets的依赖性不是Spring Boot Websockets的依赖性,并且类似地,在重新排列文件结构时,我们在程序包排列中引入了错误。

对于任何遇到类似问题的人,我的建议是:遵循教程such as this independently,以获取有关正确的文件和软件包结构的想法,然后尝试调整设置以使其匹配。