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

后端 未结 3 1815
日久生厌
日久生厌 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:22

    I took your example and dropped it in an a node app using express. Your HTML code was placed in a static HTML file under public. Your example worked fine. The code is shown below. I wanted to make sure both the socket.io script file and the HTML file were being served up properly.

    var http = require('http'),  
        io = require('socket.io'),
        express = require('express');
    
    var app = module.exports = express.createServer();
    
    // Configuration
    
    app.configure(function(){
      app.set('views', __dirname + '/views');
      app.set('view engine', 'jade');
      app.use(express.bodyParser());
      app.use(express.methodOverride());
      app.use(app.router);
      app.use(express.static(__dirname + '/public'));
    });
    
    if (!module.parent) {
      app.listen(9000);
      console.log("server started at %s", (new Date()).toUTCString());
      console.log("listening on port %d", app.address().port);
    }
    
    
    // socket.io 
    var socket = io.listen(app); 
    socket.on('connection', function(client){ 
        console.log("New client is here!");
        client.send("hello world");
        client.on('message', function(msg){ console.log("client has sent:"+msg); }) ;
        client.on('disconnect', function(){ console.log("Client has disconnected"); }) ;
        client.on('disconnect', function(){ }) 
     }); 
    

提交回复
热议问题