Long Polling Options: Nginx, PHP, Node.js

前端 未结 2 2058
一整个雨季
一整个雨季 2021-02-09 01:17

I\'m designing a long-polling app to broadcast small changes very rapidly to, possibly, a large number of users. The app will run in tandem with a website running a fairly stand

2条回答
  •  一生所求
    2021-02-09 01:50

    I, personally would use only Node.js. Instead of a long poll, you can push new information to all available clients. Node.JS is extremely fast when delivering realtime content and is capable of doing everything in one package. Also, the client side and server side is written in javascript making it easier to develop, debug, and deliver. As a developer you can see the benefits of this.

    Here is an example of an app using Node.js and the modules express, jade and NowJS. Of course this can also be used as a combination with your CMS running on apache and Node.JS serving the dynamic content. with either Nginx or a node script acting as a reverse proxy in front of this script and Apache.

    A simple chat application

    Server.js

    var express = require('express')
      , app = express.createServer()
      , nowjs = require('now')
    
    /* configure express server */
    //...
    
    app.get('/', function(req, res){
      res.render('chat')
    })
    
    var everyone = nowjs.initialize(app)
    
    // Server scoped function called by single client
    everyone.now.distributeMsg = function(msg){
      // Client scoped function of every connected client
      this.now.receiveMsg(msg)
    }
    
    app.listen(3000)
    

    chat.jade

    !!!
    html
      head
        script(type='text/javascript', src='/nowjs/now.js')
      body
        #log
        input#entry(type='text')
        input#submit(type='button')
    
    script
      $(function(){
        $('#submit').click(function(){
          now.distributeMsg($('#entry').val())
        })
    
        now.receiveMsg = function(msg){
          $('#log').append('
    ' + msg + '
    ') } })

    Yes, it REALLY is that simple and wouldn't take many more lines of code to turn this into a full featured chat application. In fact your markup and CSS would take more lines than the application code. Amazing!

提交回复
热议问题