2012-05-02 85 views
1

我在這些文件中的以下代碼:的Node.js +快速+ Socket.io:無客戶端套接字事件射擊

app.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); 
      }); 

layout.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並親自體驗。

+0

我訪問您的網站,我得到了'connected','這是測試「和」{msg:「welcome」}「。似乎工作正常。也許你的一些代理或防火牆? –

+0

嗯。有趣。當我今晚回到家時,我會嘗試,看看我是否得到相同的結果。謝謝。 –

+0

是的,在家裏工作得很好。必須是企業防火牆。謝謝。 –

回答

0

快遞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 

讓我知道,如果這有助於