Nodejs -socket.io TypeError:无法调用方法' on'未定义的

时间:2015-06-30 03:08:35

标签: node.js socket.io

我是nodejs的新手。我在socketio方法中遇到错误。

var http = require('http');
var io = require('socket.io');
var server = http.createServer(function(request, response){
    console.log('Connection');
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.write('hello world');
    response.end();
});

    io.listen(server);
io.sockets.on('connection', function(socket){
    socket.emit('message', {'message': 'hello world'});
});

这里是追溯,

io.sockets.on('connection',function(socket){
           ^
TypeError: Cannot call method 'on' of undefined
    at Object.<anonymous> (/home/vivek/Documents/nodefiles/server.js:64:12)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

我已安装套接字版本&#39; 0.9.16&#39;。我可以在哪里纠正这个问题? 提前谢谢..

1 个答案:

答案 0 :(得分:0)

http://socket.io/get-started/chat/

io.on('connection', function(socket){
  console.log('a user connected');
});

尝试删除&#34;套接字&#34;,只是&#34; io.on&#34;

io.sockets.on('connection', function(socket){
    socket.emit('message', {'message': 'hello world'});
});