HTTP Server push and WebSockets
With client-server architecture, traditionally it has been the client (e.g. your browser) that will send a request and receive a response from the server (e.g. web server). This works well in most cases, but these days there is demand for more frequent interaction and responsive data.
Consider a server application that generates events, perhaps only once per hour, and it a requirement that the client knows about this as soon as possible. Ideally we would have the server create a connection to the client, and send a message, but this is not possible using standard HTTP.
One solution is for the client to periodically send a HTTP request to server to check if any new messages are available. If no new messages are available, an ‘empty’ response is returned to the client. The client will have to keep repeating or polling the server to see if any new messages are available. This is quite wasteful on network resources, and requires a connection being created and torn down for each poll. HTTP 1.1 keepalive may help reduce the connection costs.
This is the same as polling, but instead, when the server receives the request, it will block and return a response when either:
- A new message is ready and the response is then sent to the client.
- A timeout occurs, so an ‘empty’ response is sent to the client. This timeout should be agreed upon by client and server.
For the next message, the client must initiate this process again. This is over standard HTTP request/response.
Instead of HTTP, which requires a request/response. WebSockets is a new protocol, RFC6455.
WebSockets use the initial HTTP connection, but will ‘upgrade’ and switch the protocol to WebSockets. After the connection is established, messages can be sent by either client or server. TCP connections are full duplex, and this protocol does not restrict it to half duplex like in the case of standard HTTP.
There are several implementations of WebSocket. Tomcat 7 supports this.
Browser support is currently limited. Check which browsers support websockets at caniuse.com
JSR 356: Java API for WebSocket is a Java standard for WebSocket implementations.