NodeJS + socket.io: simple Client/Server example not working

后端 未结 3 1819
日久生厌
日久生厌 2020-12-28 10:31

I’m using NodeJS v0.4.8 and the latest Version of socket.io from

npm install socket.io

on Ubuntu:

Linux m

3条回答
  •  难免孤独
    2020-12-28 11:04

    I also(like Derrish) like to use express framework to simplify my work(AWESOME :)). You can download and extract this sample from http://dl.dropbox.com/u/314941/socketio.zip. I believe you don't even have to install these modules because I have bundled them locally(just run) thanks to npm :).

    How to install:

    alfred@alfred-laptop:~/tmp/socketio$ uname -a
    Linux alfred-laptop 2.6.35-28-generic #50-Ubuntu SMP Fri Mar 18 19:00:26 UTC 2011 i686 GNU/Linux
    alfred@alfred-laptop:~/tmp$ wget http://dl.dropbox.com/u/314941/socketio.zip
    alfred@alfred-laptop:~/tmp$ unzip socketio.zip
    alfred@alfred-laptop:~/tmp$ cd socketio/
    alfred@alfred-laptop:~/tmp/socketio$ node -v
    v0.4.7
    alfred@alfred-laptop:~/tmp/socketio$ npm -v
    1.0.6
    alfred@alfred-laptop:~/tmp/socketio$ node app.js
    

    The code:

    app.js:

    // npm install express
    // npm install socket.io
    
    var sys         = require('sys'),
            express = require('express'),
            app         = express.createServer('127.0.0.1'),
            io          = require('socket.io'); 
    
    app.use(express.static(__dirname + '/public'));
    
    app.get('/', function (req, res) {
        res.send('Hello World');
    });
    
    app.listen(3000);
    
    var socket = io.listen(app); 
    
    socket.on('connection', function (client){ 
      // new client is here!
      setTimeout(function () {
            client.send('Waited two seconds!');
        }, 2000);
    
      client.on('message', function () {
      }) ;
    
      client.on('disconnect', function () {
      });
    });
    

    public/index.html:

    
    

    socket.io

    Listing of my modules:

    alfred@alfred-laptop:~/tmp/socketio$ npm ls
    /home/alfred/tmp/socketio
    ├─┬ express@2.3.11 
    │ ├── connect@1.4.6 
    │ ├── mime@1.2.2 
    │ └── qs@0.1.0 
    └── socket.io@0.6.18
    

    Installed modules(NOT necessary):

    npm install express
    npm install socket.io
    

    Browser will display:

    1. socket.io on start, but probably you can't see this because it will be replaced with connected.
    2. connected when the user connects to socket.io.
    3. After 2 seconds it will display Waited two seconds!image

提交回复
热议问题