订阅一个具有角度的websocket的连续数据

Subscribe to a continuous data with angular-websocket

本文关键字:websocket 数据 连续 一个      更新时间:2023-09-26

我正在做一个Angular应用程序,用于显示持续发送给spring服务器的数据。我的Angular应用程序连接正确,但我不知道如何订阅服务器发送的数据。我给你看我的代码:

服务器,WebSocketConfiguration

...
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(final StompEndpointRegistry registry){
        registry.addEndpoint("/random")
        .setAllowedOrigins("*")
        .withSockJS();
    }
....

服务器,数据生成器

...
@SuppressWarnings("deprecation")
@Component
public class JapcDataGenerator implements ApplicationListener<BrokerAvailabilityEvent> {
[...]
public void sendDataUpdates(int val) {
        System.out.println("sending : " + val);
        this.messagingTemplate.convertAndSend("/data", val);
    }
...

客户端,index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>WebSocket chart example</title>
    </head>
    <body ng-app="WebSocketAngularApp">
        <div ng-controller="socktCtrl">
            <p>{{data}}</p>
        </div>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
        <script type="text/javascript" src="node_modules/angular-websocket/angular-websocket.js"></script>
        <script type="text/javascript" src="resources/application.js" ></script>
    </body>
</html>

客户端应用程序.js

var socktApp = angular.module('WebSocketAngularApp',['ngWebSocket']);
socktApp.factory('mySockt',function($websocket){
    var ws = $websocket('ws://137.138.245.169:8888/serverEx/random/websocket');
    var collection = [];
    ws.onMessage( function(message){
        console.info("message: ", message);
        collection.push(JSON.parse(message.data));
    });
    ws.onOpen( function(message){
        console.log("Connection open!",message);
    });
    ws.onClose( function(){
        console.log("Closing the socket.")
    });
    ws.onError( function(message){
        console.info("Error in socket", message);
    });
    var methods = {
        collection: collection,
        get: function(){
            ws.send( JSON.stringify({action: 'data'}) );
        }
    };
    return methods;
});
socktApp.controller ('socktCtrl', function($scope, mySockt){
    $scope.data = mySockt;
});

结果显示了连接日志,但没有显示消息,因为我不知道如何订阅此数据流(行:this.messagingTemplate.convertAndSend("/data", val);)。

尝试使用ws.on('message', function...

message是从服务器发出的事件名称。