BASIC UNDERSTANDING OF WEBSOCKETS IN ANGULAR

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.


knoldus-advt-sticker


 

Written by 

Nitin Arora is Software Consultant at Knoldus Software LLP with 6 months of experience . He has done MCA from Banarsidas Chandiwala Institute of Information technology, Delhi(GGSIPU). He has a graduation degree in BCA from Jamia Hamdard. He has a sound knowledge of various programming language like C, C++, Java, and scala. Also has a deep interest in frontend development like Html, CSS, Angualar, Javascript. He is currently working in frontend technologies like Angular, Html, CSS, Bootstrap and Typescript. He is focused, hardworking, team oriented member and always exploring new Technologies, His hobbies is to play cricket, volleyball, and do coding.

1 thought on “BASIC UNDERSTANDING OF WEBSOCKETS IN ANGULAR

Leave a Reply

%d bloggers like this: