【问题标题】:How to use web sockets for communication between angular app and composer-rest-server?如何使用 Web 套接字在 Angular 应用程序和 composer-rest-server 之间进行通信?
【发布时间】:2018-06-14 01:45:53
【问题描述】:

当我生成 Hyperledger Composer REST 服务器时(请参阅 https://hyperledger.github.io/composer/latest/integrating/getting-started-rest-api),我可以选择指定是否要通过 WebSockets 启用事件发布(是/否)。

使用命令

yo hyperledger-composer

我使用生成的 rest 服务器生成了一个 angular 应用程序。

我的预期如下:

如果我没有通过 WebSockets 为 composer-rest-server 启用事件发布,那么 Angular 应用程序(为此 composer-rest-server 生成)将使用正常的 http 请求来联系 composer-rest-server。

这个期望得到了满足。 Angular 应用程序中的(自动生成的)文件 data.service.ts 使用正常的 http 请求来联系服务器。以下是该文件的摘录:

public getAll(ns: string): Observable<Type[]> {
    console.log('GetAll ' + ns + ' to ' + this.actionUrl + ns);
    return this.http.get(`${this.actionUrl}${ns}`)
      .map(this.extractData)
      .catch(this.handleError);
}

public getSingle(ns: string, id: string): Observable<Type> {
    console.log('GetSingle ' + ns);

    return this.http.get(this.actionUrl + ns + '/' + id + this.resolveSuffix)
      .map(this.extractData)
      .catch(this.handleError);
}

public add(ns: string, asset: Type): Observable<Type> {
    console.log('Entered DataService add');
    console.log('Add ' + ns);
    console.log('asset', asset);

    return this.http.post(this.actionUrl + ns, asset)
      .map(this.extractData)
      .catch(this.handleError);
}

我的另一个期望是:

如果我确实为 composer-rest-server 启用了通过 WebSockets 发布事件,那么 Angular 应用程序(为此 composer-rest-server 生成)将使用 websockets 联系 composer-rest-server。

没有达到这个期望。 Angular 应用程序中的(自动生成的)文件 data.service.ts 看起来完全相同(与是否为启用或禁用 Web 套接字的 composer-rest-server 生成 Angular 应用程序无关)。也就是使用普通的http请求来联系服务器。

这是为什么呢?如果我想使用网络套接字(用“ws”代替“http”),我是否必须手动更改文件“data.service.ts”中的代码,或者我在这里遗漏了什么?

【问题讨论】:

    标签: websocket hyperledger-composer


    【解决方案1】:

    是的,你会替换。所以你的 websockets 服务器在 ws://localhost:3000 上服务。然后您使用 WS 客户端订阅事件(您可以使用wscat 作为 WS 客户端进行测试 - 即发布事件然后看到客户端接收事件)。见https://hyperledger.github.io/composer/latest/integrating/publishing-events.html

    或写类似:

    var ws = new WebSocket('ws://www.your.server.com');
    
    
    ws.on('message', function incoming(data) {
      console.log(data);
    });
    
    // or 
    
    ws.onmessage = function (event) {
      console.log(event.data);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 2014-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多