I have an issue - I should update information for user as soon as possible, but i don't know exact time when it'll happen.
I use setInterval function that checks differences between current state and the state before checking. If there are any differences then I send an AJAX request and update info. Is it bad? I can't (or don't know how to) listen any events in that case.
And what about interval time? All users (~300 at the same time) are from local network (ping 15-20 ms). I have to refresh information immediately. Should I better use 50ms or 500ms?
If the question is not very clear just ask - I'll try to say it in other words.
Thanks in advance
Solution: Websocket
Websockets allow client applications to respond to messages initiated from the server (compare this with HTTP where the client needs to first ask the server for data via a request). A good solution would be to utilize a websocket library or framework. On the client you'll need to create a websocket connection with the server, and on the server you'll need to alert any open websockets whenever an update occurs.
The issue with interval
It doesn't scale, you could set the interval to 4000 miliseconds and still once you hit 1000 users...you are going to be slamming your server with 10000 requests and responses a minute...This will use tons of data and use processing to return nothing. Websockets will only send data to the client agent only when the event you want to send actually occurs.
Backend: PHP
Frameworks
Ratchet
Ratchet SourceCode
phpwebsocket
PHP-Websockets-Server
Simply implement one of the above frameworks as a websocket connection then you will register as a client to this endpoint and it will send data on whatever event you define.
Related
I'm looking for technique or skils to fix the ways for new web site.
This site show the read time data which located on server as file or data on memory.
I'll use Node.js for server-side. But I can't fix how to get the data and show that to web site user.
Because this data have to update per 1 second at least.
I think it is similar to the stock price page.
I know there are a lot of ways to access data like AJAX, Angular.js, Socket.io..
Also each has pros and cons.
Which platform or framework is good in this situation?
This ultimately depends on how much control you have over the server side. For data that needs to be refreshed every second, doing the polling on client side would place quite the load on the browser.
For instance, you could do it by simply using one of the many available frameworks to make http requests inside some form of interval. The downsides to this approach include:
the interval needs to be run in the background all the time while the user is on the page
the http request needs to be made for every interval to check if the data has changed
comparison of data also needs to be performed by the browser, which can be quite heavy at 1 sec intervals
If you have some server control, it would be advisable to poll the data source on the server, i.e. using a proxying microservice, and use the server to perform change checking and only send data to clients when it has changed.
You could use Websockets to communicate those changes via a "push" style message instead of making the client browser do the heavy lifting. The flow would go something like:
server starts polling when a new client starts listening on its socket
server makes http requests for each polling interval, runs comparison for each result
when result has changed, server broadcasts a socket message to all connected clients with new data
The main advantage to this is that all the client needs to do is "connect and listen". This even works with data sources you don't control – the server you provide can perform any data manipulation needed before it sends a message to the client, the source just needs to provide data when requested.
EDIT: just published a small library that accomplishes this goal: Mighty Polling ⚡️ Socket Server. Still young, examine for your use if using.
I've read a bit about Server Side Events and it seems to me that the biggest difference between SSE and Ajax Polling is that in latter you're supposed to query server yourself after each response, while with SSE a browser does that for you. Is it correct?
And in terms of server handling, there is almost no difference between SSE and Ajax Polling, with a minor difference of formatting the response in a certain way and including Content-type: text/event-stream header?
As Seabizkit basically said, one method polls the server (as much as it wants), and the other sends messages (when the server decides to send them).
If there was a single update of some data per day, can you see what the difference would be if all clients were checking once per minute, or the server sending the message once to all who have subscribed to the event?
In your question you ask if this is correct: 'the biggest difference between SSE and Ajax Polling is that in latter you're supposed to query server yourself after each response, while with SSE a browser does that for you'. To me this means you've basically asked if the browser is doing the requests for you.
Ajax Polling is asking for data - so you can check to see if it has changed etc. (similar to a web page request) on a timed basis.
An SSE sends a message to all that want to know of the change ONLY when the change has occurred.
Polling is not querying after each response, it is querying as much as you want, when you want (10 times per second if you wish, a 100, a 1,000, whatever you deem fit).
Events occur WHEN something has happened, and subscribers are then notified (hopefully just the once).
Imagine if I wanted to know if my parcel delivery driver will be turning up within the next 30 minutes.
I could call once a minute and ask - I could do this all day long if I wanted, or the driver can just call me and let me know they are 30 minutes away.
You stated in your comment to Seabizkit that client side initiates communication. No it doesn't. It adds an event handler for an event that is available on the server. The communication after that is the server sending a message to the client, be it 5 seconds later, 5 minutes later, or 50 times per second - the client doesn't request again, it has subscribed to the event and will be notified every time it fires.
Please bear in mind that this is a general explanation - not a technical one, because your question was fairly open in asking what the difference is between the two.
In the context of browsers...
The difference is: One Polls and the other responds to an Event(*).
Polling; is started at the browser end.
Make a request... receive response...do something. (usually change the UI)
Polling is expensive (relative to what you are doing!).
Polling is far easier to setup compared to handling server change on the browser.
Server side Events/Changes; is started at the server.
How to notify the browser?
Browsers out of the box have no way to respond to service side changes.
basically the browser has no idea that anything happened on the server.
You are left to handle this on your own.
Luckily library such as SignalR http://signalr.net/
Can be used simplify this a lot for you. But the complexity is still quite high compared to that of simple page with polling.
It requires you to handle socket connections between "clients".
(*) = pinch of salt, technically not worded correctly.
if this doesn't answer your question or you want more info ask.
How can i get latest or fresh data from server (if in server happened new event (for example there are 2 users x,y and x send messages to y and y get this message without refreshing page ) )?
I don't want to use setInterval because it repeats all message again and again. Is there any Technique that can i use for this ?
I heard about Ajax that technique need to send request to the server but i want when happen an event in the server and webpage get it without refreshing..
The first technique is the long polling, which sends request to the server and waits until the server sends something, for example the new message. You must re-send requests to the server each time you get a new message or your request is time out. This technique uses AJAX.
Long polling PHP example - How do I implement basic "Long Polling"?
The second is web sockets, https://en.wikipedia.org/wiki/WebSocket
this stackoverflow question deals with the implementation of websocket.
socket.io has a demo of chat application.
If you looking for bidirectional full duplex method then go for WebSockets but for just polling data from server you can use Server Sent Event as well. Adding reference links for both:
WebSocket:
http://html5demos.com/web-socket
http://en.wikipedia.org/wiki/WebSocket
HTML5 Websockets for Realtime Chat app?
SSE:
http://www.html5rocks.com/en/tutorials/eventsource/basics/
Examples:
SSE: http://demo.howopensource.com/sse/
Why make the server push data to get notifications, like using SingleR while it can be made client side?
Using a javascript timing event, that checks for recent updates at specified time intervals user can get notifications as long as he remains connected to the server.
So my question is why do more work at the server that the client can already do?
It's not more work to the server, it's less work. Suppose that you have 10000 clients (and the number could easily be in the 100K or even millions for popular web-sites) polling the server every X seconds to find out if there's new data available for them. The server would have to handle 10000 requests every X seconds even if there's no new data to return to the clients. That's huge overhead.
When the server pushes updates to the clients, the server knows when an update is available and it can send it to just the clients this data is relevant to. This reduces the network traffic significantly.
In addition it makes the client code much simpler, but I think the server is the critical concern here.
First if you didn't use server push you will not get instant update for example you can't do chat application, second why bothering the client to do job that it is not designed to do it? third you will have performance issue on the client cause like #Ash said server is a lot more powerful than a client computer.
In my application, the client is a Javascript set of functions in the browser, and it does some work - for example, playing a clip.
It uses XmlHttpRequest to talk to the server.
However, the server is allowed to abruptly close the connection since there is no other way it seems, to interrupt the client.
Can the client detect, while it is playing the clip, that the connection was closed, and so print a message and erase the page?
Any help appreciated.
thanks,
Anil
If the clip is streamed to the client, you could just stop serving it.
However, it seems like the clip is being downloaded and then played through the browser. In this instance it's probably best to use a watchdog approach as described by CookieOfFortune: Poll the server regularly (once a second or so) and get it to respond with tiny message of confirmation. When the connection is closed, get the server to respond with a negative messgage.
Unfortunately, without using a comet-like system, it's very hard to get the server to 'send' a message indicating session closure.
Bear in mind though, that as soon as the client has downloaded a clip they will be able to play it in full if they want to. Unfortunately there's no way to stop this besides switching to a streaming approach. If securing your content is a priority, I'd suggest making this change.
You can probably poll the XmlHttpRequest object, so just try to send a heartbeat every once in a while to see if the connection is closed. Otherwise, the server would have to send some signal to tell the client it is going to close the connection.
It does seem that the server cannot notify the client that the connection is closed; however the polling method suggested is not as efficient as a notification would have been.
I solved it by specifying that at the NEXT Get request, the client would be told that its session is invalid.
This was implemented by URL rewriting - appending "jsessionid=[id]" on each request sent by the Javascript functions. the servlet stores the current session id.