Time for action – running a WebSocket server
Create a project folder for our code. Inside it, create a new directory named
server
.Use a terminal or the shell command prompt to change the directory into our newly created folder.
Type the following command that will install a WebSocket server:
npm install --save ws
Create a new file named
server.js
under theserver
directory with the following content:var port = 8000; // Server code var WebSocketServer = require('ws').Server; var server = new WebSocketServer({ port: port }); server.on('connection', function(socket) { console.log("A connection established"); }); console.log("WebSocket server is running."); console.log("Listening to port " + port + ".");
Open the terminal and change to the server directory.
Type the following command to execute the server:
node server.js
You should get the following result if this works:
$ node server.js WebSocket server is running. Listening to port 8000.
What just happened?
We just created a simple server logic...