Socket.io没有发光价值 [英] Socket.io is not emitting value
本文介绍了Socket.io没有发光价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在接收socket.io发出的值时遇到问题,我没有得到问题所在。这里发布的代码请帮我解决问题。
I am having problem in receiving values emitted by socket.io, I am not getting where is the problem. Here am posting the code please help me to solve the problem.
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var spawnSync = require('child_process').spawnSync;
....
app.post('/loadImage',upload.any(),function(req, res) {
fs.readFile('/home/pathtofile/file.json','utf8',function(err,data){
if(err){
console.log(err);
}else{
//console.log(data);
var precjson = JSON.parse(data);
var loaded_filename = precjson.Filename;
io.emit('emitfilename',{loaded_filename});
}
})
}
http.listen(8080,'0.0.0.0',function(){
console.log('listening on 8080');
})
这是我收到的代码发射值:
And here is my code where I am receiving the emitted values:
<script type="text/javascript">
var socket = io.connect('http://localhost:8080');
socket.on('emitfilename',function(data){
//console.log(data);
var li = document.createElement('li');
var filename = document.createElement('h4');
filename.textContent = 'File Name:' + data.filename;
li.appendChild(filename);
document.getElementById('filenameoutput').appendChild(li);
});
</script>
我没有获取文件名,而是未定义。任何人都可以帮助我。
Instead of getting file name , I am getting undefined. Can any one please help me.
推荐答案
您不能使用io变量来发送数据。您可以使用刚刚连接的客户端的当前套接字来发送数据:
You can't use "io" variable to emit data. You can use current socket of the client that just connected to send data :
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
或使用 io.sockets 向所有套接字发送
Or use io.sockets to emit to all sockets
io.sockets.emit('users_count', clients);
希望它能解决您的问题!谢谢!
Hope it solve your problem ! Thanks !
这篇关于Socket.io没有发光价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文