How to Create A WebSocket Server with Node.js
In this tutorial, you’ll learn how to create a WebSocket server with Node.js using the websocket and http libraries. This example ties directly into the JavaScript Chat front-end solution so you can create a fully-functioning chat application.
Table of Contents
Install Dependencies
To get started, we’ll need to install the required websocket and http dependencies. Without them, the server will not be able to send and receive chat messages from users:
# npm install websocket
# npm install http
The WebSocket Server Code
Now, we’ll initialize the newly installed dependencies in our server-side code:
var websocket = require("websocket").server;
var http = require("http");
Next, let’s create two variables. One named port to define our port number so we don’t have to define it multiple times in case it changes, and connections to hold all user connections to the server:
var port = 9600;
var connections = [];
Here, we’ll create the WebSocket server and have it listen to the defined port:
var server = http.createServer();server.listen(port, function() {
console.log("Server listening on port " + port);
});var ws_server = new websocket({
httpServer: server
});
Finally, we’ll create a request event handler that listens for user requests:
ws_server.on("request", function(req) {
let connection = req.accept(null, req.origin);
connections.push(connection);
connection.on("message", function(message) {
for (let i = 0; i < connections.length; i++) {
connections[i].sendUTF(message.utf8Data);
}
});
});
When a request is received, it gets stored in a variable named connection and pushed to the global connections array. The message event listener then kicks in and loops through each existing connection through the array so that each user can receive new messages in real-time as intended.
Run the WebSocket Server
To run the WebSocket server, open a terminal window, navigate to the root folder of your project, and execute the following command:
# node app
You should see a message appear that says:
Server listening on port 9600
Conclusion
Here, you learned how to create a simple WebSocket server with Node.js that sends and receives messages from users in real time.
For the server-side WebSocket functionality, visit our Node.js WebSocket GitHub repository.
Read more here: Source link
