2012-12-11 49 views
0

我有以下服務器端代碼:沒有的NodeJS工作簡單socket.io例如

 var express = require('express') 
      , http = require('http') 
      , routes = require('./routes') 
      , io  = require('socket.io') 
      , factory = require('./serverfactory.js'); 
      var app = express(); 

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

      io.sockets.on('connection',function(socket){ 

      console.log('new user'); 

      socket.emit('hail','mysimplemsg'); 
      socket.on('customevent',function(msg){ 
       console.log(msg);  
      }); 
      }); 



     //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')); 
     }); 

     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 socket = io.connect('http://localhost:3000'); 
    socket.emit('customevent','work'); 
    socket.on('hail',function(msg){ 
     console.log(msg); 
    }); 

我期待我的git console輸出new user(它確實)然後它應該輸出work(它沒有),然後我在我的瀏覽器控制檯中得到味精mysimplemsg(它沒有)。

怎麼回事爲什麼服務器端的事件是customevent沒有被調用,爲什麼客戶端的事件是hail沒有被調用?

+0

查看下面的@ nFreeze的答案,並查看http://socket.io/#how-to-use更多示例 –

回答

0

終於搞明白了。

它在opera上正常工作,但不在chrome and firefox上。我發現this鏈接,其中的人說在服務器端插入這段代碼片段。

io.configure('development', function(){ 
    io.set('transports', ['xhr-polling']); 
}); 

現在工作正常。

+0

抱歉,我忘記提及問題中的瀏覽器問題。 – user1256956

+0

嗯,我想使用socket.io for websocket,而不是xhr-polling。不是解決方案。 – radiatedDogsInFukushima

1

我認爲問題在於您在連接之前正在從客戶端發出客戶端。嘗試添加一個連接處理器和移動客戶端發出了進去:

var socket = io.connect('http://localhost:3000');  
socket.on('hail',function(msg){ 
    console.log(msg); 
}); 
socket.on('connect',function(){ 
         console.log('connected to socket.io server'); 
         socket.emit('customevent','work'); 
        }); 

如果連接處理程序,然後命中驗證您所引用的客戶端socket.io JavaScript庫正確(玉語法):

script(type='text/javascript',src='/socket.io/socket.io.js') 
+0

thnx您的回覆我照你說的做了但仍然只能看到'new user'消息在日誌中沒有'work'消息顯示在我的git中的日誌中。 – user1256956

+0

'socket.on('connect')'不起作用。我調試代碼,客戶端沒有發送任何日誌。可能是什麼問題? – user1256956

+0

此代碼適用於我。驗證您是否正確託管了socket.io客戶端庫。 –