3

BASIC UNDERSTANDING OF WEBSOCKETS IN ANGULAR

 2 years ago
source link: https://blog.knoldus.com/basic-understanding-of-websockets-in-angular/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

BASIC UNDERSTANDING OF WEBSOCKETS IN ANGULAR

Reading Time: 2 minutes

angular-logoHere we are going to get a basic understanding of how to establish a connection between client browsers and the application server over a TCP connection using WebSockets in angular.

Websockets

WebSocket is a technology that allows two-way communication over single TCP socket. It is designed to be used between client’s browser and application server.

Role of RxJS in Websockets

  • RxJS(Reactive extension for Javascript) plays a vital role in angular, RxJS is a library which is mainly used for asynchronous code. Also, it provides an environment for implementing observables, It also helps in adapting language and browser specific environment.

  • RxJS allow us to listen to the new notifications using the WebSocket connection and perform an action if an event occurs.

Now lets see how we can implement Websockets in angular:

1: First and foremost thing we do here is import * from RxJs library which allows us to create a subject, which acts as an observer and observables both which do both listen to new notifications and also send/broadcast it to any dedicated component which subscribes to it.

import {Injectable} from '@angular/core';
import * as Rx from 'rxjs';

2: After that, we need to create new service that is WebSocket service which we will use to create and share on WebSocket connection between the components.

Injectable()
export class WebsocketService {
    public messages: Subject<any>;
    private subject: Rx.Subject;
    public ws: any;
    constructor() {
    }
    public connect(url: string): Rx.Subject {
        if (!this.subject) {
            this.subject = this.create(url);
        }
        return this.subject;
}
  • Here we create injectable service, after that, we have one private property of type Rx.Subject. This will provide access for the socket to subscribe.

  • The connect method allows us to connect to Websocket url.

Note: We can connect to only one Websocket per instance.

3: Now we create WebSocket and to create RxJS subject we need to provide observable, It will receive notification and broadcast to the subscriber. As we discuss earlier subject act as an observer and observer as well.

In another part, we create observer, which is a part of the subject which is responsible to send the message back to the WebSocket.

Note: To know more about observer refer this blog click here.

private create(url: string): Rx.Subject {
    this.ws = new WebSocket(url);
    const observable = Rx.Observable.create(
        (obs: Rx.Observer) => {
            this.ws.onmessage = obs.next.bind(obs);
            this.ws.onerror = obs.error.bind(obs);
            this.ws.onclose = obs.complete.bind(obs);
            return this.ws.close.bind(this.ws);
        }).share();

    const observer = {
        next: (data: Object) => {
            if (this.ws.readyState === WebSocket.OPEN) {
                this.ws.send(JSON.stringify(data));
            }
        }
    };
    return Rx.Subject.create(observer, observable);
}

4: In the last part we close the connection using the close method which will disconnect the WebSocket connection.

public close() {
    if (this.ws) {
        this.ws.close();
        this.subject = null;
    }
}

Conclusion: Here we get a basic understanding of how we can create and establish a connection using WebSockets in angular. I hope u guys found this blog useful. Please feel free to provide your suggestions.






About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK