WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to query the server for a response.
In Chapter 38 of our e-book course, we'll explore how to work with WebSockets in NodeJS. Before we begin, it's important to have a solid understanding of what WebSockets are and why they're useful.
What are WebSockets?
WebSockets is a technology that allows bidirectional communication between a client and a server. This means that both the client and the server can initiate communication, unlike the standard HTTP protocol where only the client can initiate communication.
WebSockets are useful in applications that require real-time communication, such as online games, live chat, among others. They allow messages to be sent and received without the need to make a full HTTP request, which can be inefficient for such applications.
Working with WebSockets in NodeJS
To work with WebSockets in NodeJS, we need to install a module called 'ws'. You can install it using npm (Node Package Manager) with the following command:
npm install ws
Once installed, we can import it into our file and start using it. Here is a basic example of how to create a WebSocket server:
const WebSocket = require('ws'); const server = new WebSocket.Server({ port: 8080 }); server.on('connection', ws => { ws.on('message', message => { console.log(`Received: ${message}`); }); ws.send('Hello! I am a WebSocket server!'); });
In this example, we create a new WebSocket server on port 8080. When a client connects to the server, it sends a greeting message. Also, whenever the server receives a message from the client, it prints it to the console.
Communicating with the customer
To communicate with the client, we can use the 'send' and 'on' methods. The 'send' method is used to send a message to the client, while the 'on' method is used to handle events such as receiving a message from the client.
Here is an example of how to use these methods:
ws.on('message', message => { console.log(`Received: ${message}`); ws.send(`Hello! You sent me: ${message}`); });
In this example, whenever we receive a message from the client, we send a reply back, echoing the message we received.
Conclusion
WebSockets are a powerful technology that allows real-time communication between a client and a server. They are especially useful in applications that require real-time updates, such as online games and live chats.
In NodeJS, we can work with WebSockets using the 'ws' module. This module allows us to create WebSocket servers, send and receive messages, and handle events.
We hope this chapter has given you a good introduction to working with WebSockets in NodeJS. In the next chapter, we'll explore how to work with databases in NodeJS.