In this chapter, we will cover the following topics:
Picture this:
A moviegoer is trying to purchase movie tickets online. He or she has selected the seats, entered the payment details, and submitted. He or she gets an error message saying that the tickets they tried to book have sold out.
Consider an application, which gives detailed information about the stock market and allows purchasing/selling stocks. When someone enters payment details and submits these details, they get an error saying that the purchase has been rejected as the price of the stock has now changed.
Initially, in applications where real-time data was required over HTTP, developers realized that they needed bidirectional communication between the client side and server side. It was generally implemented using one of the following approaches:
Although these approaches worked, using them led to some problems:
In 2011, a protocol that uses a single TCP connection for bidirectional traffic, WebSocket (RFC6455), was standardized by the Internet Engineering Task Force (IETF). By September 20, 2012, the World Wide Web Consortium (W3C) came up with the specifications for a WebSocket API.
Unlike HTTP, there is no request-response cycle in a WebSocket. Once connected, the client and server can send messages to each other. The communication can be by server and by client, that is, a two-way full duplex communication.
According to the WebSocket API:
WebSocket(url, protocols)
send(data)
methodclose()
will result in closing the connectiononopen
onmessage
onerror
onclose
A snippet using JavaScript is shown here:
var webSocket = new WebSocket('ws://localhost:9000'), webSocket.onopen = function () { webSocket.send("hello"); }; webSocket.onmessage = function (event) { console.log(event.data); }; webSocket.onclose = function () { alert("oops!! Disconnected") }
18.221.123.73