WebSockets
WebSockets is a technique for two-way communication over one (TCP) socket using the ws (unsecured) or wss(secured) protocol and can be used by any client or server application. The common use cases includes push notification, chat applications, online multi-player game or any such real-time data sharing application.
Introduction
WebSockets creates a persistent, low latency connection and allows simultaneous communication between the web-server and the client, sending data from either direction is easy and fast, and does not have the overhead of regular HTTP AJAX calls
WebSockets enables HTTP server push, as it allows a web server and client to communicate over a full-duplex TCP connection.
WebSockets can replace long-polling, which basically tries to emulate PUSH using the regular HTTP ajax calls.
Hacks to emulate bi-direction message pushing
AJAX technology was not designed to be used for the purpose of bi-direction message pushing. But when WebSockets were not around and in cases where WebSockets may not be used, the workarounds like Polling, Long Polling, Streaming, are the common.
For this blog, I will focus on the client rather than the server implementation
JavaScript WebSockets API
In order to communicate using the WebSocket protocol, you need to create a WebSocket object.
var socket = new WebSocket(URL [, protocols]);
There are mainly two WebSocket API actions:
- send(): This method is used for transmitting data to the server
- close(): This method is used to close the WebSocket connection
There are four main WebSocket API events:
- Open: This event is fired from the instance once the connection has been established between the client and the server. send() should only be called after this event has occurred. The function which gets executed is onopen.
- Message: This event occurs when the server sends some data. All of the logic to deal with the incoming data from the server is generally written here. The function which gets executed is onmessage.
- Close: This event is fired when the connection is closed by either client or server. Closing of connection can also occur because of poor connectivity. The function which gets executed is onclose.
- Error: The event is always followed by termination of connection. The function that gets executed is onerror.