At its core, WebSocket is a protocol for two-way communication between a client and a server. It enables real-time communication and eliminates the need for traditional HTTP requests and responses. With its low latency and high throughput, WebSocket is becoming increasingly popular for building real-time web applications.
In this article, we will walk you through setting up a WebSocket server in Node.js and creating a simple example app to demonstrate its capabilities.
Before we begin, there are a few prerequisites you will need:
- Node.js installed on your machine
- Basic knowledge of JavaScript and Node.js
- A text editor of your choice
Creating a WebSocket server
First, we need to create a WebSocket server. We will use the ws library, which is a popular and easy-to-use WebSocket library for Node.js.
To get started, create a new Node.js project and install the ws library using the following command:
npm install ws
Next, create a new file called server.js and add the following code:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('Hello, welcome to the WebSocket server!');
});
Let’s break down this code:
- We import the ws library and create a new WebSocket.Server instance, which listens on port 8080.
- We set up a listener for the connection event, which is fired when a new client connects to the server.
- When a client connects, we set up a listener for the message event, which is fired when the client sends a message to the server.
- We log the received message to the console and send a greeting message back to the client using the send method.
That’s it! We have successfully created a WebSocket server.
Creating a WebSocket client
Now, let’s create a WebSocket client to connect to our server. We will use the WebSocket object, which is built into modern web browsers.
Create a new file called client.html and add the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebSocket Client</title>
</head>
<body>
<div id="messages"></div>
<form>
<input type="text" id="message">
<button type="submit">Send</button>
</form>
<script>
const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = function(event) {
const messages = document.getElementById('messages');
messages.innerHTML += '<p>' + event.data + '</p>';
};
const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
event.preventDefault();
const input = document.getElementById('message');
ws.send(input.value);
input.value = '';
});
</script>
</body>
</html>
Let’s break down this code:
- We create a new WebSocket object and connect to our server using the URL ws://localhost:8080.
- We set up a listener for the message event, which is fired when the server sends a message to the client.
- When a message is received, we append it to a div element on the page.
- We set up a listener for the submit event of a form, which sends the contents of an input field to
Related Articles
JavaScript Interview Questions and Answers
Node.js Interview Questions and Answers
The Ultimate List Of Node.Js Packages For Every Web Developer
How to avoid confusion between ReactJS and React Native
Ionic Vs React Native: Which Is Better and Why?
Which Framework Is Best for Your Project – React JS or Angular JS?
Conclusion
In summary, acquiring the skills to set up a WebSocket server in Node.js can be a daunting task. However, this skill is highly valuable for any web developer. This article provides a comprehensive guide on how to create a WebSocket server with the help of an example app, ensuring that you have all the necessary resources at your fingertips.
We hope this article has been informative and beneficial to you. If you have any queries or feedback, please don’t hesitate to contact us. Thank you for reading!