Spring 4 个没有 STOMP、sockjs 的 websocket

Spring 4 websocket without STOMP,socketjs

我正在尝试在不使用 socketjs 库的情况下测试 websocket,而且我不想添加任何 stomp 连接。

我正在按照 Whosebug 问题中的示例进行操作: WebSocket with Sockjs & Spring 4 but without Stomp

所以没有 stomp 服务器,我已经成功地通过 socketjs 库与 url 连接:ws://localhost:8080/greeting/741/0tb5jpyi/websocket

现在我想删除 socketjs 库以允许原始 websocket 连接(可能是 android、ios 等设备...)

当我删除参数:.withSockJS() 时,我无法通过 websocket 连接。

我尝试了以下 URLs,但它们没有用:

ws://localhost:8080/greeting/394/0d7xi9e1/websocket not worked
ws://localhost:8080/greeting/websocket not worked
ws://localhost:8080/greeting/ not worked 

我应该使用哪个 URL 进行连接?

我在我的项目中使用没有 STOMP 的 websockets。

以下配置适用于 spring-boot

pom.xml

中添加spring启动websocket依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>${spring-boot.version}</version>
</dependency>

然后添加一个class(这里是WebSocketServerConfiguration.java),配置你的websocket:

@Configuration
@EnableWebSocket
public class WebSocketServerConfiguration implements WebSocketConfigurer {

    @Autowired
    protected MyWebSocketHandler webSocketHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(webSocketHandler, "/as");
    }
}

您终于可以编写 WebsocketHandler 了。 Spring 为 WebSocketHandlers 提供了不同的抽象 classes(在主包中:org.springframework.web.socket.handler)。我的 websocket 配置没有 STOMP,我的客户端不使用 socket.js。因此 MyWebSocketHandler 扩展了 TextWebSocketHandler 并覆盖了错误、打开和关闭连接以及接收文本的方法。

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
    ...

    @Override
    public void handleTransportError(WebSocketSession session, Throwable throwable) throws Exception {
        LOG.error("error occured at sender " + session, throwable);
        ...
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        LOG.info(String.format("Session %s closed because of %s", session.getId(), status.getReason()));

        ...
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        LOG.info("Connected ... " + session.getId());

        ...
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage jsonTextMessage) throws Exception {
        LOG.debug("message received: " + jsonTextMessage.getPayload());
        ...
    }
}

你应该使用 ws://localhost:8080/greeting:

new WebSocket('ws://localhost:8080/greeting')

我在客户端也遇到了同样的情况,客户端无法连接到服务器。

对我有用的是将波纹管 setAllowedOrigins("*") 添加到自定义处理程序。

registry.addHandler(webSocketHandler, "/app").setAllowedOrigins("*");