powtac
powtac

Reputation: 41080

How to keep a HTTP connection alive?

Is there a way to keep a HTTP connection alive with JavaScript?

Upvotes: 4

Views: 4942

Answers (2)

Roger F. Gay
Roger F. Gay

Reputation: 1971

I note that the last answer was given in 2009. Oh, how I remember the days. But lots of good things have happened since then; so I'll add this just to let people know what to look for. HTTP 1.0 provided a "keep-alive" request property that meant that the connection should be maintained for further requests. In HTTP 1.1, this became the default. You actually have to opt-out of it if you don't want to reuse the connection (and if you want to be nice about it).

The new standard for "WebSockets" actually gives you a full-duplex persistent connection. WebSockets are supported in all up-to-date versions of popular browsers and you can even use them in MSIE if you install the Google Chrome Framework (which means Google software is actually doing the work). Microsoft says IE supports it in version 10, but I haven't tried it myself. What you need then is something to connect to, like http://highlevellogic.blogspot.se/2011/09/websocket-server-demonstration_26.html

Upvotes: 5

spender
spender

Reputation: 120528

In short, I think the concept of long lived http connections in javascript really revolve around a style of communication called COMET. This can be achieved in several different ways, but essentially involves the client (using XmlHttp powers) requesting data from the server immediately, and the server withholding the response until some event triggers it. Upon receipt of this response, the client immediately makes another request (which will once again hang at the server end until something needs sending). This simulates server push, but is effectively nothing more than a delayed response used in a clever way. In the worst case, there can be fairly high latency (i.e. 2 messages need sending, so the cycle must be twice repeated, with all the costs involved) but generally, if the messaging rate is low, this gives a reasonable impression of real-time push.

Implementing the server-side for this kind of communication is far from trivial, and requires a good deal of asynchronous communications, concurrency issues and the like. It's quite easy to write an implementation that can support a few hundred users each on their own thread, but to scale to the thousands requires a much more considered approach.

Upvotes: 7

Related Questions