socket.io und node.js Einsteiger-Tutorial für Windows

Die Benutzung von socket.io mit node.js ist einfach aber wird oft unverständlich erklärt. Deshalb schreibe ich kurz das Wichtigste in wenigen Schritten nieder:

  1. node.js v0.6.16 für Windows herunterladen und installieren
  2. C:\Windows\System32\cmd.exe aufrufen
  3. Ins Projektverzeichnis wechseln, z.B.: cd C:\my_project
  4. npm install socket.io eingeben, wodurch socket.io im Ordner „C:\my_project\node_modules\socket.io“ installiert wird
  5. Die Datei C:\my_project\server.js mit diesem Inhalt anlegen:
    var io = require('socket.io').listen(72);
     
    io.sockets.on('connection', function (socket) {
      socket.emit('news', {
        hello: 'world'
      });
      socket.on('my other event', function (data) {
        console.log(data);
      });
    });
  6. Die Datei C:\my_project\client.html mit diesem Inhalt anlegen:
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8" />
        <title>Test</title>
        <style type="text/css">
          * { margin: 0; padding: 0; border: 0; }
        </style>
      </head>
      <body>  
        <script src="http://localhost:72/socket.io/socket.io.js"></script>
        <script>
          var socket = io.connect('http://localhost:72');
          socket.on('news', function (data) {
            console.log(data);
            socket.emit('my other event', { my: 'data' });
          });
        </script>
      </body>
    </html>
  7. Folgende Befehle in der cmd ausführen:
    cd C:\my_project
    node server.js
  8. C:\my_project\client.html im Browser öffnen und das Ergebnis in der JavaScript-Konsole bewundern

Error: spawn ENOTSUP when installing socket.io with npm install

If you have installed node.js v0.6.16 for Windows and you want to install socket.io with the following command:

npm install socket.io

Then it could happen that you will get this error message on Windows 7 (64-Bit):

> node install.js
 
npm ERR! Error: spawn ENOTSUP
npm ERR!     at errnoException (child_process.js:483:11)
npm ERR!     at ChildProcess.spawn (child_process.js:446:11)
npm ERR!     at Object.spawn (child_process.js:342:9)
npm ERR!     at spawn (C:\Program Files (x86)\nodejs\node_mod
npm ERR!     at exec (C:\Program Files (x86)\nodejs\node_modu
npm ERR!     at Array.0 (C:\Program Files (x86)\nodejs\node_m
npm ERR!     at EventEmitter._tickCallback (node.js:192:40)

Fortunately, there is a solution! Open this file:

C:\Program Files (x86)\nodejs\node_modules\npm\lib\utils\exec.js

Replace these two lines (around line 109 & 110):

  if (!isNaN(uid)) opts.uid = uid
  if (!isNaN(gid)) opts.gid = gid

That’s all. For more information see: Error on socket.io installing on Windows 7.

With these ones:

  if (uid && !isNaN(uid)) opts.uid = +uid
  if (gid && !isNaN(gid)) opts.gid = +gid