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

最简单的Socket.io示例的示例是什么?,第1张

最简单的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);


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

原文地址: http://outofmemory.cn/zaji/5049345.html

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

发表评论

登录后才能评论

评论列表(0条)

保存