DEV Community

Cover image for 💬NodeJs WebSocketS Chat App
alexpaper
alexpaper

Posted on

💬NodeJs WebSocketS Chat App

If you want create a super simple chat application, of course you must use socket.io, which is the absolute number one,
you can also use WebSocket API on frontend and in the backend.

WebSocket Client

The WebSocket object provides the API for creating and managing a WebSocket connection to a server,
as well as for sending and receiving data on the connection.

In the client side first of all you need to create a WebSocket connection

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

Enter fullscreen mode Exit fullscreen mode

Events

You need to create three event listeners using addEventListener(),

  1. the first one for the 'open' event,
    fired when a connection with a WebSocket is opened,

  2. the second one for the 'close' event
    fired when a connection with a WebSocket is closed,

  3. and the last one for the 'message' event,
    fired when data is received through a WebSocket.

socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

Enter fullscreen mode Exit fullscreen mode

WebSocket on the Server Side

In the backend you can also use WebSocket tecnology, in NodeJs you can install
ws library
it is very easy to implement, to install it perform this command

npm i ws

import and crete the WebSocket Server 'wss'

import WebSocket, {WebSocketServer} from 'ws';

const wss = new WebSocketServer({port:8080});

Enter fullscreen mode Exit fullscreen mode

listen for connection and send a string or an object welcome message

wss.on('connection', (ws, req)=>{

 ws.send(JSON.stringify({time: datetime, message:`💬 Welcome from the Server 🎉.`}));
});

Enter fullscreen mode Exit fullscreen mode

In this video guide you can see a super simple implementation, have a nice day!

Video Guide
🆗 👋

Top comments (0)