【问题标题】:How do I emit the data asynchronously from server to client in socket.io如何在 socket.io 中从服务器异步发送数据到客户端
【发布时间】:2016-02-21 02:54:13
【问题描述】:

在这里,我将数据从 app.js 发送到 index.html 页面。但我没有得到异步数据。

这里我正在尝试下载文件并尝试将下载进度发送到 index.html。但是在“index.html”中,下载完成后我正在获取数据。我不想要这会发生。

如果文件下载了 40%,那么浏览器中也会显示相同的内容。我该如何实现呢?谁能帮帮我...

我的 app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs');
var request = require('request');
var progress = require('request-progress');

var DOWNLOAD_DIR = '/usr/local/';
var file_name = 'jquery.js' 

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express ();
var http = require('http').createServer(app);
var io = require('socket.io')(http);



http.listen(8085, function(){
    console.log('listening on *:8085');
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

app.get('/get', function (req, res) {
progress(request('https://jqueryjs.googlecode.com/files/jquery-1.3.2-vsdoc2.js'), {
    throttle:0,   
    delay: 0       
})
.on('progress', function(state){
    console.log('received size in bytes', state.received);
    console.log('total size in bytes', state.total);
    console.log('percent', state.percent);
io.of('/socket_issue').on('connection', function (socket) {
    console.log("Socket connected :"+socket.id);
 socket.emit('message', JSON.stringify({size: state.total, received: state.received, percent: state.percent, fileName: file_name}));
});


})

.pipe(fs.createWriteStream(DOWNLOAD_DIR + file_name))
.on('error', function (err) {
 console.log("error");  
})
.on('close', function (err){
console.log("Download Complete"); 
});

 res.sendfile('views/index.html');

});




// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

我的 index.html :

<html>

<body>
<script src="http://localhost:8085/javascripts/socket.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://localhost:8085/javascripts/bootstrap.js"></script>
<script src="http://localhost:8085/javascripts/bootstrap-progressbar.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="http://localhost:8085/stylesheets/bootstrap.css" />

    <div id="progressbar"><div>

<script type="text/javascript">
var socket = io('http://localhost:8085/socket_issue');
  socket.on('connect', function(){ console.log('connected to socket'); });
  socket.on('error', function(e){ console.log('error' + e); });
  socket.on('message', function(data){
   console.log(data);


       function progress(percent, $element) {
        var progressBarWidth = percent * $element.width() / 100;
        $element.find('div').animate({ width: progressBarWidth }, 500).html(percent + "% ");
    }
    progress(JSON.parse(data).percent, $('#progressbar'));

  });
  socket.on('disconnect', function(){});
</script>
</body>
</html>

在 index.html 中(已编辑)

<body onload="timedRefresh(10000);">

<script type="text/javaScript">
    function timedRefresh(timeoutPeriod) {
     setTimeout("window.location.reload(true);",timeoutPeriod);
    }
</script>

【问题讨论】:

    标签: node.js asynchronous socket.io


    【解决方案1】:

    您正在服务器上下载一个 200kb 的文件...您的客户端需要加载更多内容。例如,仅 jquery-ui 就超过 400 KB。因此,服务器可能在客户端甚至有机会连接并监听下载进度之前就完成了文件的下载。

    作为旁注,我建议您将 io.of('socket_issue').on... 移到 .on('progress' 事件之外。每次有人请求/get时就开始监听socket.io连接是没有意义的

    【讨论】:

    • 那么,我们该如何解决这个问题......你能编辑代码吗,我真的卡在这里
    • 下载更大的文件?
    • k 我会尝试下载更大的文件
    • 我已经下载了一个.tar.gz文件。我正在获取异步数据。但问题是,我需要不断刷新html。
    • 所以您在控制台中获取数据但没有动画?
    猜你喜欢
    • 2021-01-26
    • 2018-04-27
    • 1970-01-01
    • 2017-02-16
    • 2019-04-23
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    相关资源
    最近更新 更多