DEV Community

Saunak Surani
Saunak Surani

Posted on

WebSocket in Angular: A Guide to Building Real-Time Applications

WebSockets are a great way to build real-time applications. They allow you to create a persistent connection between the client and the server, which means that data can be sent and received in real time. This makes them ideal for applications like chat, notifications, and live streaming.

In this article, we will learn how to use WebSockets in Angular. We will create a simple chat application that allows users to send messages to each other in real time.

What is a WebSocket?

A WebSocket is a persistent connection between a client and a server. It is a bi-directional connection, which means that data can be sent and received in real time. WebSockets are based on the TCP protocol, which makes them reliable and secure.

Why use WebSockets?

There are several reasons why you might want to use WebSockets in your Angular applications. Here are a few of the most important reasons:

  • Real-time communication: WebSockets allow you to create real-time applications. This means that data can be sent and received in real time, which is ideal for applications like chat, notifications, and live streaming.
  • Increased performance: WebSockets can improve the performance of your applications. This is because they eliminate the need to constantly poll the server for updates.
  • Reduced bandwidth usage: WebSockets can reduce the bandwidth usage of your applications. This is because they only send data when it is needed, rather than sending data all the time.

How to use WebSockets in Angular

To use WebSockets in Angular, you will need to install the @angular/websocket package. Once you have installed the package, you can create a WebSocket connection using the WebSocketModule.

The following code shows how to create a WebSocket connection:

import { WebSocketModule } from '@angular/websocket';

@NgModule({
  imports: [
    WebSocketModule,
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Once you have created a WebSocket connection, you can use it to send and receive data. The following code shows how to send a message to the server:

const socket = new WebSocket('ws://localhost:8080/chat');

socket.onopen = () => {
  socket.send('Hello, server!');
};
Enter fullscreen mode Exit fullscreen mode

The following code shows how to receive a message from the server:

socket.onmessage = (event) => {
  console.log(event.data);
};
Enter fullscreen mode Exit fullscreen mode

Building a chat application

Now that we know how to use WebSockets in Angular, let's build a simple chat application. The following code shows the code for the chat application:

import { Component, OnInit } from '@angular/core';
import { WebSocketModule } from '@angular/websocket';

@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.css'],
})
export class ChatComponent implements OnInit {

  messages: Array<string> = [];

  constructor(private socket: WebSocket) {}

  ngOnInit() {
    this.socket.onopen = () => {
      this.socket.send('Hello, server!');
    };

    this.socket.onmessage = (event) => {
      this.messages.push(event.data);
    };
  }

  sendMessage(message: string) {
    this.socket.send(message);
  }

}
Enter fullscreen mode Exit fullscreen mode

The code for the chat application is pretty straightforward. We create a WebSocket connection and then listen for messages from the server. When we receive a message from the server, we add it to the messages array. We can also send messages to the server by calling the sendMessage() method.

Conclusion

In this article, we learned how to use WebSockets in Angular. We created a simple chat application that allows users to send messages to each other in real time. WebSockets are a great way to build real-time applications, and they are easy to use in Angular.

Top comments (1)

Collapse
 
sloan profile image
Sloan the DEV Moderator

Hey, this article appears to have been generated with the assistance of ChatGPT or possibly some other AI tool.

We allow our community members to use AI assistance when writing articles as long as they abide by our guidelines. Please review the guidelines and edit your post to add a disclaimer.

Failure to follow these guidelines could result in DEV admin lowering the score of your post, making it less visible to the rest of the community. Or, if upon review we find this post to be particularly harmful, we may decide to unpublish it completely.

We hope you understand and take care to follow our guidelines going forward!