编辑: 我觉得最好所有人参考Socket.IO入门页面上的出色聊天示例。自从我提供了这个答案以来,API已经被简化了。话虽如此,这是针对较新API的原始答案已更新的大小。
只是因为我今天感觉很好:
index.htmlapp.js<!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>
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);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)