How does Stack Overflow notify of server-side even

2019-02-01 21:53发布

问题:

How does Stack Overflow show the answer added/edited message without a page reload?

Yes, I know it will happen with Ajax. So I opened Firebug in a browser to check it, to see whether any requests are coming in a particular interval of time. But I don't see any request coming in Firebug.

Can we perform a request without it showing in Firebug? Are there any other ideas behind this or is my concept totally wrong?

回答1:

It appears to be using HTML 5 Web Sockets. They basically keep an open connection between the server and the client and, among many other things, allow the client to define event handlers to treat new data when received from the server.

Here you'll find some basic examples and concepts about WebSockets: Introducing WebSockets: Bringing sockets to the web.

The WebSocket specification defines an API establishing "socket" connections between a web browser and a server. In plain words: There is an persistent connection between the client and the server and both parties can start sending data at any time.

There is also a live demo with server & client source code available.

You might also find the following question useful: How do real time updates work?



回答2:

To add to Xavi's answer, if you want to get started with web sockets without having to understand all the internals, you might try out Pusher, a library for multiple platforms (including PHP) that makes push notifications on the web very straightforward.

I do not work for Pusher; it's just a product I've found very useful in the past. I've always used the free version for small personal projects, though I would probably pay if I ever used it on a larger application.