Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send message from server to client in web application

Recently, I came across this kind of need. The client(web browser) requests for a task to be done asynchronously at the server side, then the client leaves it behind.

When the server finishes the task, it will notify the client by sending some message.

So, my question is:

Is there a way to send message(plain text, json, etc) from the server side to the client initiatively?

like image 593
xiaohan2012 Avatar asked Feb 21 '12 07:02

xiaohan2012


1 Answers

Off the top of my head, two possible solutions come to mind:

The first, most common (and safest) solution to this will probably be AJAX long-polling, that is, setting up an ajax query on the client to periodically make a request and do something with the response. For example, setting up a resource that returns your "completed" message when the server side processing is complete. It's not ideal, given your question, but it is certainly feasible and pretty reliable.

To actually use push technology (which is precisely what you're asking, but not necessarily what you really need), you should take a look at WebSockets. If you take a look at that link you will see in the body of the article the list of browsers supporting the technology, and depending on your use case, you may or may not wish to investigate further.

I personally deal with a lot of old browsers so the ajax polling would be my go to guy. Assuming this is a semi long running process, polling every 2-5 seconds should not upset your users too much. This won't be good for real-time chats or anything, but for "I parsed your 200M excel file" it should be fine.

like image 80
jholder Avatar answered Sep 19 '22 05:09

jholder