0

I would like to ask if someone knows how can I notify a user that looks at a page of my website with a push notification (i.e. make my server notify the user that there's something to him).

I understand the polling mechanism (I can implement it through a simple loop with a setInterval() in Javascript and pass a callback that makes an async XMLHttpRequest or a getJSON), but what about the push mechanism?

I guess I need to make a sort of a call with the server that should tell the client that it has something for him??? Assuming that my website is in PHP, is there a way to make it?

Thanks for the attention!

tonix
  • 6,671
  • 13
  • 75
  • 136

2 Answers2

1

The network topology usually does not allow real push notifications. Certainly a browser won't. What you can do is using a special kind of polling strategy that comes close: "long polls".

Basically these are ajax based poll requests that are not immediately answered by the server. The server only sends an answer when some event is available or a defined timeout is reached. In that case the poll will be instantiated again right away by the client. In the mean time the socket stays open, the request does not consume any resources. In effect this allows push notifications.

How do I implement basic "Long Polling"?

Also obviously google will spit out tons of hits if you search for "php long poll".

Community
  • 1
  • 1
arkascha
  • 41,620
  • 7
  • 58
  • 90
  • Sorry, when you say that the long poll request is not immediately answered by the server you mean that PHP delays the script execution e.g. using the uspleep($microsec); function based on some events? – tonix Apr 16 '14 at 11:10
  • 1
    Exactly, the response is delayed by purpose. Either time based or event based. – arkascha Apr 16 '14 at 11:10
  • Is this uspleep() approach resource consuming for the server? – tonix Apr 17 '14 at 20:15
  • 1
    No, nott really, since the process really sleeps until woken again. But you can't help that anyway, this is common to all approaches, same for example for the WebSockets solution mentioned by @Mykola in this answer which does more or less the same thing in the end: a socket is held open all the time. There is no other way: the network topology requires the communication to be initiated by the client, so either you have to accept an open socket or a polling strategy which will consume much more power and load on both sides since in that case the processes do _not_ sleep. – arkascha Apr 18 '14 at 07:47
1

Take a look at WebSocket - wiki.
Currently WebSocket supported by all popular browsers. You can check it here.

For PHP there is a good solution - Ratchet (http://socketo.me/)

Mykola
  • 123
  • 1
  • 7