获得"没有方法' "使用socket.io时出错

时间:2015-11-17 06:03:27

标签: node.js socket.io

我得到"没有方法' "我尝试使用socket.io时出错。任何人都可以帮我解决这个问题......

在这一行,我正面临错误,

var chat = socketio.of("/socket").on('connection',onSocketConnected);

我的app.js:

var fs = require('fs')

    , http = require('http')

    , socketio = require('socket.io');

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

var app = express ();

var chat = socketio.of("/socket").on('connection',onSocketConnected);

function onSocketConnected(socket){
   console.log("connected :"+socket.id);  
}

//in your existing callback function of progress
//send info to client 
var callback = function(state){
    console.log('received size in bytes', state.received);
    console.log('total size in bytes', state.total);
    console.log('percent', state.percent);
    io.sockets.emit('message', JSON.stringify({size: state.total, received: state.received, percent: state.percent, fileName: fileName}));

} 

progress(request('https://www.google.com/images/srpr/logo3w.png'), {
    throttle:0,   
    delay: 0       
})
.on('progress', callback) 

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

2 个答案:

答案 0 :(得分:2)

您的socketio变量未正确初始化。你需要这样的东西:

var socketio = require('socket.io').listen(server);

其中server是活动的HTTP服务器对象。

您的代码是:

var socketio = require('socket.io');

这只是获取socket.io模块,而不是初始化和活动的实例。

因此,您的socketio变量是socket.io模块,而不是初始化和活动的实例。它是具有.of()方法的实例。

答案 1 :(得分:1)

我想问题出在您的声明socketio = require('socket.io')中。官方文件说:

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

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