2

I have a PHP application where people post different status messages. I want to implement realtime notifications in it.

That is if a user posts something, immediately other users accessing the site will get a prompt on their screen about a new post. I have heard you can use node.js to implement it. But I don't know how exactly it can be done. Any help will kindly be appreciated.

4

2 回答 2

3

I suggest you to take a look at socket.io. Client send a message to node, node can save to db (or forward with a RESTful call to your php application) and notify all clients.

It's not php but only nodejs and js. Enjoy ;)

Example

SERVER:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

CLIENT

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

You have to write what you want to be done in the client in on("yourEvent", function() { ...

于 2013-07-26T15:42:56.223 回答
0

You can use Long Polling technique. Long polling is the name used to describe a technique which:

  1. An AJAX request is made (utilizing a javascript framework such as jQuery)
  2. The server waits for the data requested to be available, loops, and sleeps (your server-side PHP script)
  3. This loop repeats after data is returned to the client and processed (usually in your AJAX request's onComplete callback function)

or

Try a server side pushing tech like Commet.

于 2013-07-26T15:48:59.160 回答