1

我在这些文件中有以下代码:

应用程序.js:

/**
 * Module dependencies.
 */

var io = require('socket.io')
  , express = require('express')  
  , mongoose = require('mongoose')
  , models = require('./models')(mongoose)
  , routes = require('./routes')(models);
var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.use(express.cookieParser());
  app.use(express.session({secret:'123abc',key:'express.sid'}));
  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'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

app.get('/', routes.index);

var sio = io.listen(app);
app.listen(3000);


sio.sockets.on('connection', function(socket) {
    socket.send('this is a test');
    console.log('socket connected, sessionID ' + socket.handshake.sessionID);
    socket.emit('welcome', {msg: 'welcome'});
});

var parseCookie = require('connect').utils.parseCookie;

sio.set('authorization', function (data, accept) {
        if (data.headers.cookie) {
                data.cookie = parseCookie(data.headers.cookie);
                data.sessionID = data.cookie['express.sid'];
        } else {
                return accept('No cookie transmitted.', false);
        }

        accept(null, true);
});

console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

/javascripts/socket.js:

var socket = io.connect('http://173.255.229.76', {port:3000});
            socket.on('connect', function(data) {
                console.log('connected');
            });
            socket.on('message', function(data) {
                    console.log(data);
            });

            socket.on('welcome', function(data) {
                    console.log(data);
            });

布局.jade:

!!!
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    script(src="/socket.io/socket.io.js")
    script(src="/javascripts/socket.js")
  body!= body

当客户端连接时,我在控制台中获得调试信息,显示我期望的所有输出,但客户端上没有任何内容。没有任何事件被调用,并且没有数据记录到控制台。我究竟做错了什么?随意访问网址: http: //173.255.229.76 :3000并亲自查看。

4

1 回答 1

0

对于 express 3,您需要创建一个 http 服务器实例才能使用 socket.io

var express = require('express'),
app = express(),
io = require('socket.io'),
http = require('http');
//routes and config ...

var s = http.createServer(app);
var sio = io.listen(s);
s.listen(8080)
//do whatever

让我知道这是否有帮助

于 2012-12-26T16:15:27.287 回答