WebSocket
Modern applications often need an established two-way server connection for receiving real-time data. The best option for that purpose is using WebSocket connection. Entropy provides a powerful channel API for dealing with WebSockets.
Configuration
The configuration for WebSocket integration is stored in the .env
file variables:
.env
PORT=5050
WebSocket Channels
First though, you should be introduced to a concept of WebSocket channels. Channel is a single class used for transmitting events with authorization logic.
src/chats/chat.channel.ts
import { Authorizer } from '@entropy/http'; import { Broadcaster, Channel } from '@entropy/web_socket'; @Channel('chats/:id') export class ChatChannel extends Broadcaster implements Authorizer { public authorize(): boolean { return true; } public sendMessage(message: string) { this.broadcast({ payload: message, }); } }
String argument passed to decorator is channel name with dynamic parameter. The authorize
method is used to determine whether authenticated user is authorized to join the channel on the client side.
Server Event Emitting
Emitting events on the server side can be done using the broadcast
method of Broadcaster
class.
For example, if you want to create a live chat, you may create a channel method sendMessage
like that:
src/chats/chat.channel.ts
// ... public sendMessage(message: string, id: number) { this.broadcast({ payload: message, channel: `chats/${id}`, // Broadcast to specific channel with dynamic parameter }); } // And use it in a controller: this.chatChannel.sendMessage(`Hello, ${user.name}!`, chat.id);
Client Side Event Receiving
Now we are able to receive broadcasts on the client side using JavaScript WebSocket API. The example implementation you can see below:
views/chats/chat.atom.html
<main> <h1>Chat (ID {{ $request.params.id }}) <form id="chat"> <input type="text" name="message" placeholder="Enter your message..."> <button>Send</button> </form> </main> <script> const socket = new WebSocket('ws://localhost:5050'); const chatId = '{{ $request.params.id }}'; const form = document.querySelector('#chat'); form.addEventListener('submit', (event) => { event.preventDefault(); const data = new FormData(form); fetch(`/chats/${chatId}`, { method: 'POST', body: data, }); }); socket.onmessage = (event) => { const data = JSON.parse(event.data); if (data.channel === `chats/${chatId}`) { console.log(`Received essage: ${data.payload.message}`); } }; </script>