通过 AngularJS (angular-websocket-service) 和 Spring 引导使用 Websockets 通知注册客户端

Notify registered clients using Websockets with AngularJS (angular-websocket-service) and Spring Boot

我是 AngularJS 的新手,也是 FullStack 开发的新手。我当前应用程序的架构已经设置好,最好不要更改(出于安全原因)。到目前为止,我可以使用 angular-websocket-service 向服务器发送消息。这是前端服务的代码片段:

proxiMiamApp.service('WebSocketService', function ($websocket) {
var wsEndpoint = {};

this.openWsEndpoint = function () {
    wsEndpoint = $websocket.connect("ws://localhost:9000/proximiamHandler");
    console.log(wsEndpoint);
    return wsEndpoint;
}

this.sendMessage = function(){
    if($.isEmptyObject(this.wsEndpoint)){
        this.openWsEndpoint();
    }

    eventUser = {

        idEvent : '1',
        idUser : '49'
    };

    wsEndpoint.register('/eventUser', function(){

        console.log('Register OK!');
    });
    console.log('Ready!');
    wsEndpoint.emit('/eventUser',eventUser);


}});

至于后端,我正在使用 WebSocketHandler 接口的实现:

@Controller
public class ProximiamHandler implements WebSocketHandler {

@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
    System.out.println("afterConntectionEstablished called");
}

@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {

    System.out.println("handleMessage called");
    // My code here...

}

@Override
public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
    System.out.println("handleTransportError called");
}

@Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
    System.out.println("afterConnectionClosed called");
}

@Override
public boolean supportsPartialMessages() {
    return true;
}}

通过 Spring WebSocketConfigurer

调用 WebSocketHandler 的实现
@Configuration
@EnableWebSocket
@Controller
public class WebSocketConfig implements WebSocketConfigurer {

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(myHandler(), "/proximiamHandler").setAllowedOrigins("*");
}

@Bean
public WebSocketHandler myHandler() {
    return new ProximiamHandler();
}}

My questions are:

  1. Can I notify subscribed clients using this architecture?
  2. If yes, how can I do it?
  3. Is there a way to return something to subscribed clients from the server? (an Object or a String for instance)

在此先感谢您的帮助

我可以使用此架构通知订阅的客户吗? => 是的。

如果是,我该怎么做? => 基于 Spring 网络套接字 API,您必须保留通过 "afterConnectionEstablished" 回调传递给您的“WebSocketSession”。 使用 Web 套接字会话的 sendMessage() API 向客户端发送通知。

有没有办法 return 从服务器向订阅的客户端发送一些东西? (例如一个对象或一个字符串) => 您可以将数据格式化为 JSON 或 XML 并使用 "WebSocketMessage" 包装并将其传递给客户端。

我从未在 spring 上工作过,但是,我是根据我对网络套接字的了解来回答这个问题的。看看有没有帮助。