簡體   English   中英

不使用socket.io和node.js發出/接收事件

[英]Not emitting/receiving events with socket.io and node.js

所以我有這個非常基本的socket.io設置,你可能已經看過很多次了。

請注意,這里的文件是通過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"}]}

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

非常感謝提前!

如果你的projectnamestock ,那么這就是你的問題。 Socket.IO認為你正在使用命名空間 您可以在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文件夾中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM