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');
Events
You need to create three event listeners using addEventListener(),
the first one for the 'open' event,
fired when a connection with a WebSocket is opened,the second one for the 'close' event
fired when a connection with a WebSocket is closed,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);
});
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});
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 🎉.`}));
});
In this video guide you can see a super simple implementation, have a nice day!
Video Guide
🆗 👋
Top comments (0)