栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430716.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号