码迷,mamicode.com
首页 > Web开发 > 详细

nodejs实现简单消息推送

时间:2014-12-23 17:18:24      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

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实现简单消息推送

标签:

原文地址:http://www.cnblogs.com/feilv/p/4180357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!