开发实时更新网站的最佳方式[关闭]

I am trying to develop a website that shows a post automatically when it was posted by another user, or a user receives notification when a message has been sent to him, basically something that works like Facebook. Without needing to reload the page or hitting F5.

I have been working with Javascript and PHP for years and the only way to keep page updated as far as I know is by using AJAX requests continuously.

This is an example (Checking message from dataBase):

setInterval(function() {
    $ajax({
      url: "http://myweb.com/checkmessage.php",
      type: "POST",
      data: {value: userID},
      dataType: "json",
      success: function(result){

              //If true do something and update message inbox

         }
    });
}, 500);

This basically sends requests every 0.5 seconds to my PHP file where I have access to my database and I check for new messages and return them. Thanks to this code I can get message notification in real-time without having to update my website.

But honestly, from performance perspective it's very bad practice to have hundreds AJAX requests sending every 0.5 seconds at once, it slows down the website.

That's why I am asking here if there is a better way to implement this, I have been checking Facebook and the way it was implemented pure mystery to me. I still don't know how do they do it, to have such massive updates on a page and just a few calls (You can check by yourself opening facebook waiting till it loads then open google developer tools, go to network and see it by your eyes!).

You would use websockets for such a scenario. Using HTTP, AJAX polling or AJAX long polling would essentially add a lot of overhead on the network due to many request/response cycles being involved which in turn intrinsically involve all the connection setup and validation steps each time.

However, implementing this from scratch is usually not an option. You will find a lot of PaaS, IaaS options. I've used Ably before and it seemed to perfectly solve the purpose.

Basically even if you are trying to implement the underlying functionality yourself, you would need to use the Publish/Subscribe architecture using which an event is pushed everytime something changes (like a user posts a new post on FB) and this event will in turn be broadcasted to all the subscribers. On the subscribers end, you would implement the logic to handle the event.

Websockets are a perfect solution to this use-case because they allow full-duplex and persistent connections, so the server can utilise the push paradigm to continually push updates as the data updates.

Hope this helps!

Some of the possible approches are:

  • web sockets
  • long polling
  • push api

You can read about them and make your choice.

Have a look at Pusher (pusher.com). They have a free tier that you can use and then establish whether this will be sufficient for your needs.

You can use their demo - it's surprisingly easy.

In your PHP you trigger a "push" like this:

<?php
  require __DIR__ . '/vendor/autoload.php';

  $options = array(
    'cluster' => 'eu',
    'encrypted' => true
  );
  $pusher = new Pusher\Pusher(
    'key1',
    'key2',
    'key3',
    $options
  );

  $data['message'] = 'hello world';
  $pusher->trigger('my-channel', 'my-event', $data);
?>

And then in your HTML you listen out for the push:

<!DOCTYPE html>
<head>
  <title>Pusher Test</title>
  <script src="https://js.pusher.com/4.1/pusher.min.js"></script>
  <script>

    // Enable pusher logging - don't include this in production
    Pusher.logToConsole = true;

    var pusher = new Pusher('your-key', {
      cluster: 'eu',
      encrypted: true
    });

    var channel = pusher.subscribe('my-channel');
    channel.bind('my-event', function(data) {
      alert(data.message);
    });
  </script>
</head>

So, if you push some JSON then you'll receive this almost immediately in your HTML page. You can then do what you need.

You Can use Pusher with event broadcasting system for your requirement. And to improvise that you can use Angular or Vue