2012-06-07 38 views
4

所以我有這個非常基本的socket.io設置,你可能已經看過一千次了。不發送/接收事件與socket.io和node.js

請不要在這裏通過apache提供文件。

服務器(app.js)

var io = require('socket.io').listen(8080); 

io.sockets.on('connection', function(socket){ 
    socket.emit('server ready', {msg: 'hi'}) ; 

    socket.on('random event', function(data) { 
     console.log('received'); 
    }) 
}); 

客戶

$(document).ready(function() { 
    var socket = io.connect('http://127.0.0.1:8080/projectname/server/'); 

    socket.on('server ready', function(data){ 
     console.log('server ready!'); 
    }); 

    socket.emit('random event', {hurr: 'durr'}); 
}); 

但是,我得到的唯一輸出是

debug - websocket writing 5:::{"name":"server ready","args":[{"msg":"hi"}]} 
在節點控制檯

和客戶端沒有任何東西安慰。這是錯誤的。

我已經嘗試了socket.io網站的基本示例,它顯示了完全相同的行爲。它將發射的數據記錄在節點控制檯中,但似乎沒有其他事情發生。

編輯:經進一步調查,訪問了Firefox中的網站會在節點控制檯不同的輸出:

info - handshake authorized 178702677759276313 
    debug - setting request GET /socket.io/1/xhr-polling/178702677759276313?t=1339080239192 
    debug - setting poll timeout 
    debug - client authorized for 
    debug - clearing poll timeout 
    debug - xhr-polling writing 1:: 
    debug - set close timeout for client 178702677759276313 
    debug - xhr-polling received data packet �17�1::/stock/server/�66�5::/stock/server/:{"name":"random event","args":[{"hurr":"durr"}]} 
    debug - setting request GET /socket.io/1/xhr-polling/178702677759276313?t=1339080239263 
    debug - setting poll timeout 
    debug - clearing poll timeout 
    debug - xhr-polling writing 5:::{"name":"server ready","args":[{"msg":"hi"}]} 

這看起來像fromt他客戶端實際到達服務器發出的數據。但是,它似乎並沒有解決實際問題:console.log行以及客戶端和服務器端都沒有執行。 此輸出來自Firefox 5.0.1,它似乎回退到xhr。

非常感謝!

+0

爲什麼通過'http://127.0.0.1:8080 /項目名稱/服務器/'和'不是HTTP://127.0.0.1:8080 /'或'簡單io.connect()'? – alessioalex

+0

我完全不知道,這更多的是反覆試驗的結果。這是服務器app.js的位置。其他一切都會在socket.io.js上引發一個客戶端404。也許這是因爲我有一個同時在本地主機上運行的apache web服務器。 – ngmir

+0

你是通過Apache代理Node還是什麼? – alessioalex

回答

3

如果您的projectnamestock,那就是您的問題。 Socket.IO認爲你正在使用namespace。您可以在xhr-polling received data packet日誌行中看到這一點。因爲您沒有在服務器端的該名稱空間上進行偵聽,所以不會調用console.log

您應該從您的客戶端連接地址中刪除/projectname/server,並正確引用客戶端庫,以便您不會得到404。無論是Apache代理問題還是在您的頭文件中修復script src取決於您當前的設置。我無法從你提供的代碼中知道。

PS:Socket.io應該爲http://127.0.0.1:8080/socket.io/socket.io.js服務客戶端庫,但是您可能會通過引用apache服務器在端口80服務的文檔中的資產來運行跨域來源策略問題。快速修復可能是從您的apache服務器提供客戶端lib,該服務器位於socket.io-client模塊dist文件夾中。

+0

謝謝!關於你的PS,這就是我剛剛做的。 – ngmir