Spring 在没有 SockJS 的情况下启动 Websocket

Spring boot Websocket without SockJS

我已经为此苦苦挣扎了至少两周。我对 websockets 很陌生。我对休息端点有很好的经验。

我的用例很简单。客户端启动一个 websocket 连接,向服务器发送一些信息,服务器使用该信息,并以固定的时间间隔(比如每 5 秒)向客户端发送回一些信息。 我按照这里的教程 - https://spring.io/guides/gs/messaging-stomp-websocket/ 正如所解释的那样,它完美地工作。 按照上面的教程,client发起一个http请求,升级为websocket。

在我的案例中,前端是一个 angular 10 应用程序,前端开发人员更喜欢使用 rxjs/websocket 而不想使用 SockJS client,因为他确信我们不必支持任何旧版浏览器,这就是我感到震惊的地方。 显然 rxjs/websocketws:// 协议中需要 url。

根据以下代码片段,我认为我的等效 ws 协议是 ws://localhost:8080/test 不过好像不行。我不确定哪里出了问题。非常感谢任何帮助!

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer
{

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

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

}

根据教程,我更改了 app.js,如下所示以进行测试。

function connect() {
    // var socket = new SockJS('http://localhost:8080/test'); This works perfectly
    // stompClient = Stomp.over(socket);
    ws = new WebSocket('ws://localhost:8080/test');
    stompClient = Stomp.client(ws);

    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/' + $("#site").val(), function (message) {
            showMessageSentFromServer(JSON.stringify(message.body));
        });
    });
}

当我打开 chrome 的开发者工具并检查时,我看到 websocket 连接已经建立并升级,或者就是我所看到的。但是,在控制台中,我看到如下错误日志。我不确定哪里出了问题。

网络截图:

控制台失败日志:

stomp.min.js:8 Uncaught DOMException: Failed to construct 'WebSocket': The URL '[object WebSocket]' is invalid.
    at Object.client (http://localhost:8080/webjars/stomp-websocket/stomp.min.js:8:7229)
    at connect (http://localhost:8080/app.js:18:25)
    at HTMLButtonElement.<anonymous> (http://localhost:8080/app.js:54:9)
    at HTMLButtonElement.dispatch (http://localhost:8080/webjars/jquery/jquery.min.js:3:10315)
    at HTMLButtonElement.q.handle (http://localhost:8080/webjars/jquery/jquery.min.js:3:8342)

长话短说,我设法通过删除 withSockJS() 在服务器端禁用了 SockJs。那么我的等效 ws 协议 URL 是什么?

此外,除此之外,我面临的另一个挑战是,如何设置一个计划的进程,该进程可以根据客户端的输入将消息发送到客户端已订阅的 websocket 主题。我知道使用 @Scheduled 注释设置预定进程很容易。但就我而言,我想要来自客户的一些输入,这是计划过程中所需要的。

此外,请分享您拥有的任何资源或示例,这些资源或示例解释了如何使用 rxjs

实现对主题的 websocket stomp 客户端订阅

我不是专家,但我认为所有 WebSocket URI 都使用 ws: 或 wss: 方案来实现安全的 WebSocket。要更熟悉 WebSockets,您应该看看 How Do Websockets Work?.

当我开始使用 Websockets 时,我从 Androidhive; Building Group Chat App using Sockets

中学到了很多东西

我不太习惯 spring Websockets,但在过去我使用 Java EE 时它相对简单。您所要做的就是使用带注释的@ServerEndpoint 配置服务器端点。从那里你可以使用带有注释的函数

@OnMessage
public String onMessage(String message, Session session) {
    ...
}

@OnOpen
public void onOpen(Session session) {
    ...
    // Here you can start a session handler
    // which will send message every 5 sec or so.
    s = new SessionHandler(session, id);
    s.start();
}

@OnClose
public void onClose(Session session) {
    ...
}

这是您发送消息的方式

public void send(String msg) throws IOException {
    session.getBasicRemote().sendText(msg);
    // session.getBasicRemote().flushBatch(); 
}

这是javascript的一面,

var wsUri = "ws://" + (document.location.hostname === "" ? "localhost" : document.location.hostname) + ":" +
            (document.location.port === "" ? "80" : document.location.port);

var websocket;
function connect() {
    websocket = new WebSocket(wsUri);

    websocket.onopen = function (evt) {
        onOpen(evt);
    };
    websocket.onmessage = function (evt) {
        onMessage(evt);
    };
    websocket.onerror = function (evt) {
        onError(evt);
    };

    websocket.onclose = function (evt) {
        onClose(evt);
    };
}

connect();

我知道这是针对 Java EE 的,但也许您可以考虑使用 Java EE,它不再那么糟糕了。如果您有兴趣,请查看这个更深入的示例 How to build applications with the WebSocket API for Java EE and Jakarta EE

我做了两个简单的更改就解决了这个问题。

  1. 我通过向 WebSocketConfig 添加两个端点来使我的后端支持 wshttp 协议,如下所示 - 一个有 [=17=,另一个没有 sockjs ] 如下所示,这使我的后端在支持两种协议建立 websocket 连接方面更加灵活。我不知道为什么 spring 文档或其他地方没有提到这一点。或许,人家以为是暗示吧!
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer
{

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

        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry)
        {
                registry.addEndpoint("/test"); // This will allow you to use ws://localhost:8080/test to establish websocket connection
                registry.addEndpoint("/test").withSockJS(); // This will allow you to use http://localhost:8080/test to establish websocket connection
        }

}
  1. 正如 @arturgrzesiak 在之前的评论中指出的那样,传递给 Stomp.client(url) 的参数有错误我很傻,传递的是 ws 对象而不是普通的 url.
stompClient = Stomp.client('ws://localhost:8080/test');

最后,

如果有人想使用SockJS客户端连接,他们可以使用

连接
var socket = new SockJS('http://localhost:8080/test');
stompClient = Stomp.over(socket);

如果有人只想使用普通 Websocket 对象进行连接,请使用以下内容。

stompClient = Stomp.client('ws://localhost:8080/test');

我发布了这个解决方案,因为这对有类似痛苦经历的人有用,他们可能会发现它有用。

如评论所述:

From the stomp docs: var url = "ws://localhost:15674/ws"; var client = Stomp.client(url); - you should pass just url string instead of already created websocket object.