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

最简单的Socket.io示例的示例是什么?

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

最简单的Socket.io示例的示例是什么?

编辑: 我觉得最好所有人参考Socket.IO入门页面上的出色聊天示例。自从我提供了这个答案以来,API已经被简化了。话虽如此,这是针对较新API的原始答案已更新的大小。

只是因为我今天感觉很好:

index.html

<!doctype html><html>    <head>        <script src='/socket.io/socket.io.js'></script>        <script> var socket = io(); socket.on('welcome', function(data) {     addMessage(data.message);     // Respond with a message including this clients' id sent from the server     socket.emit('i am client', {data: 'foo!', id: data.id}); }); socket.on('time', function(data) {     addMessage(data.time); }); socket.on('error', console.error.bind(console)); socket.on('message', console.log.bind(console)); function addMessage(message) {     var text = document.createTextNode(message),         el = document.createElement('li'),         messages = document.getElementById('messages');     el.appendChild(text);     messages.appendChild(el); }        </script>    </head>    <body>        <ul id='messages'></ul>    </body></html>

app.js

var http = require('http'),    fs = require('fs'),    // NEVER use a Sync function except at start-up!    index = fs.readFileSync(__dirname + '/index.html');// Send index.html to all requestsvar app = http.createServer(function(req, res) {    res.writeHead(200, {'Content-Type': 'text/html'});    res.end(index);});// Socket.io server listens to our appvar io = require('socket.io').listen(app);// Send current time to all connected clientsfunction sendTime() {    io.emit('time', { time: new Date().toJSON() });}// Send current time every 10 secssetInterval(sendTime, 10000);// Emit welcome message on connectionio.on('connection', function(socket) {    // Use socket to communicate with this particular client only, sending it it's own id    socket.emit('welcome', { message: 'Welcome!', id: socket.id });    socket.on('i am client', console.log);});app.listen(3000);


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

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

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