Time for action – running a WebSocket server

  1. Create a project folder for our code. Inside it, create a new directory named server.
  2. Use a terminal or the shell command prompt to change the directory into our newly created folder.
  3. Type the following command that will install a WebSocket server:
    npm install --save ws
  4. Create a new file named server.js under the server 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 + ".");
  5. Open the terminal and change to the server directory. ...

Get HTML5 Game Development by Example : Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.