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
library. This example ties directly into the front-end JavaScript solution so you can create a fully-functioning real-time chat application.
Install Dependency
To get started, install the required websocket
dependency. Without it, the server will not be able to send and receive chat messages from users:
# npm install websocket
The Code
Now, let's initialize all dependencies in our code:
var websocket = require("websocket").server;
var http = require("http");
Next, we'll 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 initialize WebSockets and have them 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 incoming 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 throughout the array so that each user can receive new messages in real-time.
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.
You can get the Node.js WebSocket code from our GitHub repository.
Comments
There are no comments yet. Start the conversation!