server1.js
var http = require(‘http‘); var express = require(‘express‘); var sio = require(‘socket.io‘); var app = express(); app.use(express.static(__dirname + ‘/‘)); var server = http.createServer(app); server.listen(3001, ‘127.0.0.1‘); var io = sio.listen(server); var users = []; io.sockets.on(‘connection‘, function(socket) { console.log(‘a socket is connect, id: ‘ + socket.id); io.sockets.emit(‘conn‘, socket.id); }); setInterval(function() { console.log(‘推送消息‘); io.sockets.emit(‘conn‘, ‘推送消息‘); }, 1000);
client1.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script type="text/javascript" src="socket.io.js"></script> <script type="text/javascript"> window.onload = function() { var socket = io.connect(‘http://127.0.0.1:3001‘); socket.on(‘connect‘, function() { socket.on(‘conn‘, function(id) { document.getElementById(‘div1‘).innerHTML += id + ‘<br>‘; }); }); } </script> </head> <body> <div id="div1"></div> </body> </html>
server2.js
var http = require(‘http‘); var sio = require(‘socket.io‘); var server = http.createServer(); server.listen(3002, ‘127.0.0.1‘); var io = sio.listen(server); console.log(‘简单消息推送服务器运行...‘); setInterval(function() { io.sockets.emit(‘conn‘, ‘推送内容‘); }, 1000);
client2.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script type="text/javascript" src="socket.io.js"></script> <head> <body> <div id="div1"></div> <script> window.onload = init(); function init() { var socket = io.connect(‘http://127.0.0.1:3002‘); socket.on(‘conn‘, function(msg) { document.getElementById(‘div1‘).innerHTML += msg + ‘<br>‘; }); } </script> </body> </html>
时间: 2024-11-08 23:02:22