首页 > 代码库 > nodejs实现简单消息推送
nodejs实现简单消息推送
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>
nodejs实现简单消息推送
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。