linux – Socket.IO无法调用’on’

前端之家收集整理的这篇文章主要介绍了linux – Socket.IO无法调用’on’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在制作一个简单的node.js应用程序并打算使用socket.io但到目前为止我无法启动服务器.

这是我的代码

  1. var http = require('http'),io = require('socket.io'),fs = require('fs');
  2.  
  3. http.createServer(function(request,response){
  4. fs.readFile(__dirname + '/index.html',function(err,data){
  5. if(err){
  6. response.writeHead(500,{'Content-Type': 'text/plain'});
  7. return response.end('Error');
  8. }
  9. response.writeHead(200,{'Content-Type': 'text/html'});
  10. response.end(data);
  11. });
  12. }).listen(1337);
  13.  
  14. io.sockets.on('connection',function(socket){
  15. socket.emit('pic',{ addr: '/pic.jpg' });
  16. socket.on('status',function(data){
  17. console.log(data);
  18. })
  19. })

这是我收到的输出

  1. [root@ip-10-224-55-226 node]# node server.js
  2.  
  3. /srv/node/server.js:16
  4. io.sockets.on('connection',function(socket){
  5. ^
  6. TypeError: Cannot call method 'on' of undefined
  7. at Object.<anonymous> (/srv/node/server.js:16:12)
  8. at Module._compile (module.js:449:26)
  9. at Object.Module._extensions..js (module.js:467:10)
  10. at Module.load (module.js:356:32)
  11. at Function.Module._load (module.js:312:12)
  12. at Module.runMain (module.js:492:10)
  13. at process.startup.processNextTick.process._tickCallback (node.js:244:9)
  14. [root@ip-10-224-55-226 node]#

Socket.IO由NPM安装,似乎位于/root/node_modules/socket.io中
因此,我已将该目录的sym-link(ln -s)发送到我的服务器根目录所在的/ srv / node.

解决方法

io只是一个图书馆.您想要侦听连接到一个特定实例:
  1. var http = require('http'),fs = require('fs');
  2.  
  3. var serv = http.createServer(function(request,{'Content-Type': 'text/html'});
  4. response.end(data);
  5. });
  6. });
  7. serv.listen(1337);
  8.  
  9. // Bind socket.io to server
  10. var serv_io = io.listen(serv);
  11. serv_io.sockets.on('connection',function(data){
  12. console.log(data);
  13. })
  14. });

猜你在找的Linux相关文章