如何使用网络套接字在 angular 应用程序和 composer-rest-server 之间进行通信?

How to use web sockets for communication between angular app and composer-rest-server?

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

使用命令

yo hyperledger-composer

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

我的预期是:

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

达到了这个期望。 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 看起来完全相同(无论 angular 应用程序是为启用还是禁用 Web 套接字的 composer-rest-server 生成的).也就是说,使用正常的 http 请求来联系服务器。

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

是的,你会替代。所以你的 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);
}

等等