【问题标题】:How to connect to Spring WebSocket request in backend?如何在后端连接到 Spring WebSocket 请求?
【发布时间】:2020-06-09 05:29:36
【问题描述】:

我正在尝试向我的 Spring Boot 应用程序添加一个 websocket 连接,我习惯于只处理 Https 协议,但我需要有这个 websocket 连接才能继续向前端发送通知。我已经添加了这个依赖<org.springframework.boot:spring-boot-starter-websocket:2.0.0.RELEASE>,因为由于某种原因我的应用程序没有执行 spring-starter-websocket 的 2.4.5 版本。

我有一个配置类来启用这个连接,这是这个类的代码:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/api").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config){
        config.enableSimpleBroker("/topic/");
    }
}

为了处理连接,我在控制器中创建了这个方法:

@Autowired
SimpMessagingTemplate simpMessagingTemplate;

@MessageMapping("/news")
    public void broadcastNews(@Payload String message) {
        this.simpMessagingTemplate.convertAndSend("/topic/news", message);
    }

为了测试这个连接,我正在使用这个站点:https://www.websocket.in/test-online,并且我正在尝试连接到这个 url:wss//:localhost:8085/mywebsockets

当我尝试连接时,我的控制台会响应:

2020-02-25 10:32:09.707  INFO 16000 --- [MessageBroker-1] o.s.w.s.c.WebSocketMessageBrokerStats    : WebSocketSession[0 current WS(0)-HttpStream(0)-HttpPoll(0), 0 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(0)-CONNECTED(0)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], outboundChannelpool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], sockJsScheduler[pool size = 3, active threads = 1, queued tasks = 2, completed tasks = 0]

网站无法连接,但没有出现任何错误,我已经等了 10 多分钟,没有其他任何反应。

我不明白我做错了什么,我已经尝试与 Https 连接,但它根本不起作用,也许我没有找到我的 url 必须是什么,因为我的应用程序收到了请求用于连接,因为它在控制台中响应。

【问题讨论】:

  • I'm trying to connect to this url: wss//:localhost:8085/mywebsockets。该网站将在其主机上而不是在您的机器上查找 websocket 服务器。您应该告诉网站连接到您的公共 IP。您可以从这里获取您的 IP whatismyip.com

标签: java spring-boot websocket


【解决方案1】:

如果你想连接到wss//:localhost:8085/mywebsockets,你必须将入口点设置为这个url,而不是addEndpoint("/api")。您应该允许跨源请求进行测试:

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/mywebsockets").setAllowedOrigins("*").withSockJS();
    }

您可以使用这样的 chrome 扩展来测试您的 websocket 连接: https://chrome.google.com/webstore/detail/apic-complete-api-solutio/ggnhohnkfcpcanfekomdkjffnfcjnjam

选择api testing -> ws 并连接到http://localhost:8085/mywebsockets,客户端会自动切换协议到ws://

本教程帮助我正确设置了所有内容: http://kojotdev.com/2019/07/using-spring-websocket-stomp-application-with-vue-js/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    相关资源
    最近更新 更多