SpringBoot+WebSocket问题:Failed to register @ServerEndpoint class

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot+WebSocket问题:Failed to register @ServerEndpoint class相关的知识,希望对你有一定的参考价值。

参考技术A 项目中用到了WebSocket,在开发时没有问题,但是部署到测试服务器时却出现了问题。

经过对比分析后,发现开发时的容器是 SpringBoot内置Tomcat ,使用ServerEndpointExporter扫描注册ServerEndpoint,而测试服务器的容器是 Tomcat ,使用自带jar包中的ServerApplicationConfig扫描注册ServerEndpoint,不同的容器使用不同的扫描机制。所以在开发环境需要注入ServerEndpointExporter,而在测试、生产环境则不需要注入,而是使用Tomcat容器去管理。

无法在服务器(SpringBoot)和 iOS 之间建立 WebSocket 连接

【中文标题】无法在服务器(SpringBoot)和 iOS 之间建立 WebSocket 连接【英文标题】:Cant able to make WebSocket connection between server(SpringBoot) and iOS 【发布时间】:2017-10-27 11:13:43 【问题描述】:

我正在尝试在 iOS 和服务器(SpringBoot)之间建立 WebSocket 连接。在服务器端,我们正在使用这样的 WebSocket 连接。

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer 

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) 
        config.enableSimpleBroker(URLMapping.WS_SEND);
        config.setApplicationDestinationPrefixes(URLMapping.WS_PREFIX);
    

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) 
        registry.addEndpoint("/api/v1/transactionSocket").setAllowedOrigins("*").withSockJS();
    

在 IOS 中,我使用 StompClient 库来建立 WebSocket 连接。

func makeConnection() 
    let client = StompClient(url: URL(string: "/api/v1/transactionSocket")!)
    client.delegate = self
    client.connect() 


func disconnectConnection() 
    client.disconnect()
    print("Disconnecting :\(client)")


func stompClientDidConnected(_ client: StompClient) 
    print("Stomp got connected: \(client) .... \(client.isConnected)")
    // client.subscribe("API")


func stompClient(_ client: StompClient, didErrorOccurred error: NSError) 
    print("Stomp Error occures \(client)   errror: \(error)")


func stompClient(_ client: StompClient, didReceivedData data: Data, fromDestination destination: String) 
    print("Cliemt: \(client)  Data: \(data) destination: \(destination)")

在运行时,既没有建立连接,也没有调用 'stompClientDidConnected' 委托方法。

我没怎么用过WebSocket。所以无法理解是什么原因。任何帮助将不胜感激。

谢谢

【问题讨论】:

您的客户端对象是 makeConnection() 中的一个局部变量。一旦该方法超出范围,客户端对象就会从内存中释放。 在顶部声明客户端对象后..我在“didErrorOccurred”委托方法中收到此错误日志“Error Domain=WebSocket Code=200 “Invalid HTTP upgrade” 【参考方案1】:

你可以使用StopmClientLib进行socket连接,也有subscribe方法。

https://github.com/wrathchaos/StompClientLib

【讨论】:

成功了……终于找到了解决办法。我使用了这个库并通过在 url 中附加“/websocket”来强制客户端和服务器之间的连接。

以上是关于SpringBoot+WebSocket问题:Failed to register @ServerEndpoint class的主要内容,如果未能解决你的问题,请参考以下文章

Websocket教程SpringBoot+Maven整合(目录)

springboot2 -广播式WebSocket

无法在服务器(SpringBoot)和 iOS 之间建立 WebSocket 连接

Springboot-WebSocket初探-获取HttpSession问题

springboot websocket实现过程中踩过的坑

Springboot +WebSocket学习