var app = require("http").createServer(handler); // handler defined below
var io = require("socket.io")(app);
var fs = require('fs');
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + "/index.html",
function (err, data) {
if (err) {
res.writeHead(500);
return res.end("Error loading index.html");
}
res.writeHead(200);
res.end("Hell World");
});
}
io.on('connection', function(socket){
socket.on('dataChanged', function(data){console.log("Hello World")});
})
io.emit('dataChanged', 'this is a test')
//index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('dataChanged', function(data){console.log("Hello World")});
</script>
我正在尝试实现这个微不足道的功能,但它不起作用。我哪里出错了,我没有看到日志。套接字事件未注册。
最佳答案
好吧,这里有三件事。
1.您的res.end
正在发送Hell world
但它应该发送 data
res.end("Hell World");
应该是
res.end(data);
这是因为我们想要显示index.html文件而不是hello world
2.你的index.html调用socket.io js文件错误
<script src="/node_modules/socket.io/socket.io.js"></script>
应该是
<script src="/socket.io/socket.io.js"></script>
这是因为您无法引用这样的文件,因为您的代码中没有它的逻辑。然而,socket.io 确实有它的逻辑,并且可以这样调用
3.在客户端使用emit
在你的index.html中更改此代码
socket.on('dataChanged', function(data){console.log("Hello World")});
到
socket.emit('dataChanged', 'this is a test')
并删除
io.emit('dataChanged', 'this is a test')
来自你的nodejs文件
现在您可以从控制台看到 Hello World
关于javascript - socket.io 不适用于简单用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34371037/