WebSocket protocol is used for persistent communication of data between the server and client. We can transfer data in both directions in the form of a "packet" using HTTP and HTTPS protocols.
ws
using npmTo use WebSockets in JavaScript, we have to install the ws
package by using npm
.
$ npm i ws
Before using WebSockets in JavaScript, we must import it into our file or project. To do this, we can use both import
and require
depending upon our application.
import Websocket from 'ws'
const WebSocket = require(ws);
In this example, we are simply making a messaging app. When we run the code below, we will see a simple messaging app.
const WebSocket = require(`ws`); const wss = new WebSocket(`ws://localhost:3000`); wss.onmessage = function (e) { console.log("I'm client") let message = JSON.parse(e.data); console.log(message); };
ws
package.ws.on
.ws
package.ws.onmessage
that will receive the message.message
variable.Free Resources