Socket.io-在node.js中的单独文件中侦听事件

Socket.io-在node.js中的单独文件中侦听事件,第1张

Socket.io-在node.js中的单独文件中侦听事件

不,只需使用相同的“ io”对象

File1.js

exports = module.exports = function(io){  io.sockets.on('connection', function (socket) {    socket.on('file1Event', function () {      console.log('file1Event triggered');    });  });}

File2.js

exports = module.exports = function(io){  io.sockets.on('connection', function (socket) {    socket.on('file2Event', function () {      console.log('file2Event triggered');    });  });}

app.js

var app = require('http').createServer(handler)  , io = require('socket.io').listen(app)  , fs = require('fs')  , file1 = require('./File1')(io)  , file2 = require('./File2')(io)app.listen(3000);function handler (req, res) {  fs.readFile(__dirname + '/index.html',  function (err, data) {    if (err) {      res.writeHead(500);      return res.end('Error loading index.html');    }    res.writeHead(200);    res.end(data);  });}

index.html

<script src="/socket.io/socket.io.js"></script><script>  var socket = io.connect('http://localhost');  socket.emit('file1Event');  // 'file1Event triggered' will be shown  socket.emit('file2Event');  // 'file2Event triggered' will be shown</script>


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5103190.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-17
下一篇2022-11-17

发表评论

登录后才能评论

评论列表(0条)

    保存