How to use web sockets for communication between a

2019-07-22 15:37发布

问题:

When I generate the Hyperledger Composer REST server (see https://hyperledger.github.io/composer/latest/integrating/getting-started-rest-api), I have the option to specify whether I want to enable event publication over WebSockets (Yes/No).

Using the command

yo hyperledger-composer

I generated an angular app using the generated rest server.

What I expected was the following:

If I did NOT enable event publication over WebSockets for the composer-rest-server, then the angular app (generated for this composer-rest-server) would use normal http requests to contact the composer-rest-server.

This expectation was met. The (automatically generated) file data.service.ts within the angular app uses normal http requests to contact the server. Here's an excerpt from the file:

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);
}

The other expectation I had was this:

If I DID enable event publication over WebSockets for the composer-rest-server, then the angular app (generated for this composer-rest-server) would use websockets to contact the composer-rest-server.

This expectation was NOT met. The (automatically generated) file data.service.ts within the angular app, looks exactly the same (independent of whether the angular app was generated for a composer-rest-server with web sockets enabled or disabled). That is, normal http requests were used to contact the server.

Why is that? Do I have to change the code in the file "data.service.ts" manually, if I want to use web sockets (substituting "ws" for "http") or am I missing something here?

回答1:

Yes, you would substitute. So your websockets server is serving on ws://localhost:3000 . You then use a WS client to subscribe to events (you can use wscat as a WS client to test - ie publish an event then see the client receive the event) . See https://hyperledger.github.io/composer/latest/integrating/publishing-events.html

or write something like:

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);
}

etc