Nodejs和一个简单的web页面消息推送服务

前言:

英语能力有限,所以不能叫做纯翻译,大概比例是70%翻译,20%理解,10%自由发挥

原文:

http://www.gianlucaguarini.com/blog/nodejs-and-a-simple-push-notification-server/

简述:

用socket.io建立服务端和客户端的双向连接,当服务端的xml文件发生变化时,向客户端推送xml内容

------------- start -----------------------

在本文中我将向你展示如何使用nodejssocket.io创建一个push(推送)服务。通常如果我们想更新web应用的一些内容,我们采用javascript论询(timer)或者简单地使用AJAX请求web服务以此来实现更新页面内容。这对于小用户量的应用来说是个不错的解决方案,但是使用这种方法当大量用户同一时间在你的页面会怎么样?


你应该知道,AJAX请求=客户端请求头(header)+服务端响应头(response header)+数据(data)。(更多关于此的信息请见这篇文章websocket performance(websocket性能))。所以如果你的web应用有大量用户使用大量AJAX请求来下载更新内容,甚至可能包含一些不需要更新的无用AJAX请求,你的服务器会被迫支持大量不必要的轮询。解决这个大问题你可能有两个解决方案:

1、你是google,所以你有大量的服务器群允许你做任何无用功、允许你挥霍、浪费

2、你潇洒地使用跨浏览器解决方案构建一个简洁的推送消息服务。

下面我将向你展示如何构建一个简洁的消息推送服务,先从代码开始。首先你需要在你的服务器上安装nodejs。然后对于这个实例我们需要引用socket.io和xml2js两个nodejs模块到我们的项目中。你可以通过命令行使用"npm(node包管理node package manager)"安装任意的nodejs模块,像这样:

$ npm install socket.io
$ npm install xml2json

下面新建一个server.js文件,它包含所有将运行在服务器上的nodejs代码。

var app = require('http').createServer(handler),
  io = require('socket.io').listen(app),
  parser = new require('xml2json'),
  fs = require('fs');

// 创建一个服务,端口号是8000 ( localhost:8000 )
app.listen(8000);

console.log('server listening on localhost:8000');

// 加载 client.html 页面
function handler(req, res) {
  fs.readFile(__dirname + '/client.html', function(err, data) {
    if (err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error loading client.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}

// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {
  console.log(__dirname);
  // watching the xml file
  fs.watchFile(__dirname + '/example.xml', function(curr, prev) {
    // 如果xml文件发生了改变,读取xml文件
    fs.readFile(__dirname + '/example.xml', function(err, data) {
      if (err) throw err;
      // xml转换为json
      var json = parser.toJson(data);
      // 发送新的数据到客户端
      socket.volatile.emit('notification', json);
    });
  });

});

创建一个简单的example.xml文件。


<span style="font-size:18px;"><?xml version="1.0" encoding="ISO-8859-1"?>
<test>
    <sample>Hello world!</sample>
</test></span>

最后你可以自由地创建你的前端页面client.html,当example.xml发生变化时会你的数据将会被推送。

<html>
    <head>
    <!--
     * Author:      Gianluca Guarini
     * Contact:     gianluca.guarini@gmail.com
     * Website:     http://www.gianlucaguarini.com/
     * Twitter:     @gianlucaguarini
    -->
        <title>Push notification server</title>
    </head>
    <body>
        <time></time>
        <div id="container">Try to change your xml data to update this content</div>
    <script src="socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
    // creating a new websocket
    var socket = io.connect('http://localhost:8000');
    // on every message recived we print the new datas inside the #container div
    socket.on('notification', function (data) {
        // convert the json string into a valid javascript object
        var _data = JSON.parse(data);

        $('#container').html(_data.test.sample);
        $('time').html('Last Update:' + new Date());
    });
    </script>
    </body>
</html>

【此处作者还提供了个视频,需要翻墙看,在youtube】

正是因为有socket.io才有了这个简单又跨平台的解决方案,我们在html页面和服务器间创建了一个双向连接,只有xml发生改变时才会推送新的数据,可以利用的技术包括新的websocket api甚至是回退到flash技术( 更多socket.io去这里)

下载教程

如果你喜欢这篇文章,你可以读我的 新文章——如何让你的Nodejs推送消息服务连接mysql数据库。


---------------- end --------------------

其实我要找的是app的安卓推送,跑偏了==!


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值