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

ngm*_*mir 5 javascript node.js socket.io

所以我有这个非常基本的 socket.io 设置,您可能已经看过一千次了。

\n\n

请注意,这里的文件是通过 apache 提供的。

\n\n

服务器(app.js)

\n\n
var io = require(\'socket.io\').listen(8080);\n\nio.sockets.on(\'connection\', function(socket){ \n    socket.emit(\'server ready\', {msg: \'hi\'}) ;\n\n    socket.on(\'random event\', function(data) {\n        console.log(\'received\');\n    })\n}); \n
Run Code Online (Sandbox Code Playgroud)\n\n

客户

\n\n
$(document).ready(function() {\n    var socket = io.connect(\'http://127.0.0.1:8080/projectname/server/\');\n\n    socket.on(\'server ready\', function(data){ \n        console.log(\'server ready!\'); \n    });\n\n    socket.emit(\'random event\', {hurr: \'durr\'});\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

然而,我得到的唯一输出是

\n\n
 debug - websocket writing 5:::{"name":"server ready","args":[{"msg":"hi"}]}\n
Run Code Online (Sandbox Code Playgroud)\n\n

在节点控制台中,而在客户端控制台中没有任何内容。这是错误的。

\n\n

我已经尝试了 socket.io 网站上的基本示例,它显示了完全相同的行为。它将发出的数据记录在节点控制台中,但似乎没有发生任何其他事情。

\n\n

编辑:经过进一步调查,在 Firefox 中访问该站点会在节点控制台中创建不同的输出:

\n\n
info  - handshake authorized 178702677759276313\n   debug - setting request GET /socket.io/1/xhr-polling/178702677759276313?t=1339080239192\n   debug - setting poll timeout\n   debug - client authorized for \n   debug - clearing poll timeout\n   debug - xhr-polling writing 1::\n   debug - set close timeout for client 178702677759276313\n   debug - xhr-polling received data packet \xef\xbf\xbd17\xef\xbf\xbd1::/stock/server/\xef\xbf\xbd66\xef\xbf\xbd5::/stock/server/:{"name":"random event","args":[{"hurr":"durr"}]}\n   debug - setting request GET /socket.io/1/xhr-polling/178702677759276313?t=1339080239263\n   debug - setting poll timeout\n   debug - clearing poll timeout\n   debug - xhr-polling writing 5:::{"name":"server ready","args":[{"msg":"hi"}]}\n
Run Code Online (Sandbox Code Playgroud)\n\n

看起来从客户端发出的数据实际上到达了服务器。然而,它似乎并没有解决实际问题:console.log 行以及客户端和服务器端都没有执行。此输出来自 Firefox 5.0.1,它似乎回退到 xhr。

\n\n

预先非常感谢!

\n

Wes*_*son 4

如果你projectnamestock,那就是你的问题。Socket.IO 认为您正在使用命名空间。您可以在日志行中看到这一点xhr-polling received data packetconsole.log永远不会被调用,因为您没有在服务器端侦听该名称空间。

您应该摆脱/projectname/server您的客户端连接地址并正确引用客户端库,这样您就不会收到 404。这是 Apache 代理问题还是修复script src标头中的问题取决于您当前的设置。从您提供的代码中我无法判断。

PS:Socket.io 应该在 处提供客户端库服务http://127.0.0.1:8080/socket.io/socket.io.js,但是通过从 apache 服务器在端口 80 处提供的文档中引用该资产,您可能会遇到跨域源策略问题。快速修复可能是从以下位置提供客户端库服务:你的 apache 服务器,位于socket.io-client模块dist文件夹中。