TutorialsPoint Web Sockets
TutorialsPoint Web Sockets
This protocol defines a full duplex communication from the ground up. Web sockets take
a step forward in bringing desktop rich functionalities to the web browsers. It represents
an evolution, which was awaited for a long time in client/server web technology.
Audience
This tutorial has been prepared for anyone who has a basic knowledge of Protocols and
understanding of HTTP. After completing this tutorial, you will find yourself at a moderate
level of expertise in understanding what makes Web Sockets different from the traditional
HTTP request/response pattern.
Prerequisites
Before you start proceeding with this tutorial, we are assuming that you are already aware
about the basics of JavaScript and understanding of the HTTP protocol. If you are not well
aware of these concepts, then we will suggest you to go through our short tutorials on
JavaScript and HTTP.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@[Link]
i
Web Sockets
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
Copyright & Disclaimer ..................................................................................................................................... i
Table of Contents ............................................................................................................................................ ii
ii
Web Sockets
iii
Web Sockets
1
Web Sockets
1. Web Sockets – Overview
In literal terms, handshaking can be defined as gripping and shaking of right hands by two
individuals, as to symbolize greeting, congratulations, agreement or farewell. In computer
science, handshaking is a process that ensures the server is in sync with its clients.
Handshaking is the basic concept of Web Socket protocol.
The following diagram shows the server handshake with various clients:
The key points of Web Sockets are true concurrency and optimization of
performance, resulting in more responsive and rich web applications.
2
Web Sockets
Web socket protocol is being standardized, which means real time communication
between web servers and clients is possible with the help of this protocol.
Web sockets are transforming to cross platform standard for real time
communication between a client and the server.
This standard enables new kind of the applications. Businesses for real time web
application can speed up with the help of this technology.
URL
HTTP has its own set of schemas such as http and https. Web socket protocol also has
similar schema defined in its URL pattern.
Browser Support
The latest specification of Web Socket protocol is defined as RFC 6455 – a proposed
standard.
RFC 6455 is supported by various browsers like Internet Explorer, Mozilla Firefox, Google
Chrome, Safari, and Opera.
3
Web Sockets
2. Web Sockets – Duplex Communication
Before diving to the need of Web sockets, it is necessary to have a look at the existing
techniques, which are used for duplex communication between the server and the
client. They are as follows:
1. Polling
2. Long Polling
3. Streaming
4. Postback and AJAX
5. HTML5
Polling
Polling can be defined as a method, which performs periodic requests regardless of the
data that exists in the transmission. The periodic requests are sent in a synchronous way.
The client makes a periodic request in a specified time interval to the client. The response
of the server includes available data or some warning message in it.
Long Polling
Long polling, as the name suggests, includes similar technique like polling. The client and
the server keep the connection active until some data is fetched or timeout occurs. If the
connection is lost due to some reasons, the client can start over and perform sequential
request.
Long polling is nothing but performance improvement over polling process, but constant
requests may slow down the process.
Streaming
It is considered as the best option for real-time data transmission. The server keeps the
connection open and active with the client until and unless the required data is being
fetched. In this case, the connection is said to be open indefinitely. Streaming includes
HTTP headers which increases the file size, increasing delay. This can be considered as a
major drawback.
AJAX
AJAX is based on Javascript's XmlHttpRequest Object. It is an abbreviated form of
Asynchronous Javascript and XML. XmlHttpRequest Object allows execution of the
Javascript without reloading the complete web page. AJAX sends and receives only a
portion of the web page.
var xhttp;
if ([Link]) {
xhttp = new XMLHttpRequest();
} else {
4
Web Sockets
HTML5
HTML5 is a robust framework for developing and designing web applications. The main
pillars include Mark-up, CSS3 and Javascript APIs together.
The code snippet given below describes the declaration of HTML5 and its doctype.
<!DOCTYPE html>
Server technologies advanced which allowed dynamic server pages - pages whose content
was generated based on a query.
Soon, the requirement to have more dynamic web pages lead to the availability of Dynamic
Hypertext Mark-up Language (DHTML). All thanks to JavaScript. Over the following years,
we saw cross frame communication in an attempt to avoid page reloads followed by
HTTP Polling within frames.
However, none of these solutions offered a truly standardized cross browser solution to
real-time bi-directional communication between a server and a client.
This gave rise to the need of Web Sockets Protocol. It gave rise to full-duplex
communication bringing desktop-rich functionality to all web browsers.
5
Web Sockets
3. Web Sockets – Functionalities
Web Socket represents a major upgrade in the history of web communications. Before its
existence, all communication between the web clients and the servers relied only on HTTP.
Web Socket helps in dynamic flow of the connections that are persistent full duplex. Full
duplex refers to the communication from both the ends with considerable fast speed.
It is termed as a game changer because of its efficiency of overcoming all the drawbacks
of existing protocols.
Web Socket is a transport layer on top of which any other protocol can run. The
Web Socket API supports the ability to define sub-protocols: protocol libraries that
can interpret specific protocols.
Examples of such protocols include XMPP, STOMP, and AMQP. The developers no
longer have to think in terms of the HTTP request-response paradigm.
The only requirement on the browser-side is to run a JavaScript library that can
interpret the Web Socket handshake, establish and maintain a Web Socket
connection.
On the server side, the industry standard is to use existing protocol libraries that
run on top of TCP and leverage a Web Socket Gateway.
6
Web Sockets
Web Socket connections are initiated via HTTP; HTTP servers typically interpret Web
Socket handshakes as an Upgrade request.
Web Sockets can both be a complementary add-on to an existing HTTP environment and
can provide the required infrastructure to add web functionality. It relies on more
advanced, full duplex protocols that allow data to flow in both directions between client
and server.
The steps for establishing the connection of Web Socket are as follows:
2. The process begins with the client sending a regular HTTP request to the server.
3. An Upgrade header is requested. In this request, it informs the server that request
is for Web Socket connection.
4. Web Socket URLs use the ws scheme. They are also used for secure Web Socket
connections, which are the equivalent to HTTPs.
7
Web Sockets
8
Web Sockets
4. Web Sockets – Implementation
Web Sockets occupy a key role not only in the web but also in the mobile industry. The
importance of Web Sockets is given below.
Web Sockets as the name indicates, are related to the web. Web consists of a bunch
of techniques for some browsers; it is a broad communication platform for vast
number of devices, including desktop computers, laptops, tablets and smart phones.
HTML5 app that utilizes Web Sockets will work on any HTML5 enabled web browser.
Web socket is supported in the mainstream operating systems. All key players in the
mobile industry provide Web Socket APIs in own native apps.
Web sockets are said to be a full duplex communication. The approach of Web Sockets
works well for certain categories of web application such as chat room, where the
updates from client as well as server are shared simultaneously.
Web Sockets, a part of the HTML5 specification, allow full duplex communication between
web pages and a remote host. The protocol is designed to achieve the following benefits,
which can be considered as the key points:
Reduce unnecessary network traffic and latency using full duplex through a
single connection (instead of two).
Streaming through proxies and firewalls, with the support of upstream and
downstream communication simultaneously.
9
Web Sockets
10
Web Sockets
5. Web Sockets – Events and Actions
It is necessary to initialize the connection to the server from client for communication
between them. For initializing the connection, creation of Javascript object with the URL
with the remote or local server is required.
The URL mentioned above is a public address that can be used for testing and experiments.
The [Link] server is always up and when it receives the message and sends it
back to the client.
This is the most important step to ensure that application works correctly.
Open
Message
Close
Error
Each of the events are handled by implementing the functions like onopen, onmessage,
onclose and onerror functions respectively. It can also be implemented with the help of
addEventListener method.
The brief overview of the events and functions are described as follows:
Open
Once the connection has been established between the client and the server, the open
event is fired from Web Socket instance. It is called as the initial handshake between client
and server. The event, which is raised once the connection is established, is called
onopen.
Message
Message event happens usually when the server sends some data. Messages sent by the
server to the client can include plain text messages, binary data or images. Whenever the
data is sent, the onmessage function is fired.
Close
Close event marks the end of the communication between server and the client. Closing
the connection is possible with the help of onclose event. After marking the end of
communication with the help of onclose event, no messages can be further transferred
between the server and the client. Closing the event can happen due to poor connectivity
as well.
11
Web Sockets
Error
Error marks for some mistake, which happens during the communication. It is marked
with the help of onerror event. Onerror is always followed by termination of connection.
The detailed description of each and every event is discussed in further chapters.
send( )
close( )
send ( )
This action is usually preferred for some communication with the server, which includes
sending messages, which includes text files, binary data or images.
A chat message, which is sent with the help of send() action, is as follows:
close ( )
This method stands for goodbye handshake. It terminates the connection completely and
no data can be transferred until the connection is re-established.
12
Web Sockets
[Link]( );
}
}
It is also possible to close the connection deliberately with the help of following code
snippet:
[Link](1000,”Deliberate Connection”);
13
Web Sockets
6. Web Sockets – Opening Connections
Once a connection has been established between the client and the server, the open event
is fired from Web Socket instance. It is called as the initial handshake between client and
server.
The event, which is raised once the connection is established, is called the onopen.
Creating Web Socket connections is really simple. All you have to do is call the WebSocket
constructor and pass in the URL of your server.
Once the connection has been established, the open event will be fired on your Web
Socket instance.
onopen refers to the initial handshake between client and the server which has lead to
the first deal and the web application is ready to transmit the data.
The following code snippet describes opening the connection of Web Socket protocol:
[Link] = function(event) {
[Link](“Connection established”);
// Display user friendly messages for the successful establishment of connection
[Link] = [Link](“status”);
[Link]= ”Connection established”;
}
It is a good practice to provide appropriate feedback to the users waiting for the Web
Socket connection to be established. However, it is always noted that Web Socket
connections are comparatively fast.
The demo of the Web Socket connection established is documented in the given URL:
[Link]
14
Web Sockets
A snapshot of the connection establishment and response to the user is shown below:
Establishing an open state allows full duplex communication and transfer of messages until
the connection is terminated.
Example
Building up the client-HTML5 file.
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var wsUri = "[Link]
var output;
function init() {
output = [Link]("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
[Link] = function(evt) {
onOpen(evt)
};
}
function onOpen(evt) {
writeToScreen("CONNECTED");
}
[Link]("load", init, false);
15
Web Sockets
</script>
<h2>WebSocket Test</h2>
<div id="output"></div>
</html>
The above HTML5 and JavaScript file shows the implementation of two events of Web
Socket, namely:
onOpen: establishes connection with the server and also sends the status.
16
Web Sockets
7. Web Sockets – Handling Errors
Once a connection has been established between the client and the server, an open event
is fired from the Web Socket instance. Error are generated for mistakes, which take place
during the communication. It is marked with the help of onerror event. Onerror is always
followed by termination of connection.
The onerror event is fired when something wrong occurs between the communications.
The event onerror is followed by a connection termination, which is a close event.
A good practice is to always inform the user about the unexpected error and try to
reconnect them.
[Link] = function(event) {
[Link]("Error occurred.");
// Inform the user about the error.
var label = [Link]("status-label");
[Link] = "Error: " + event;
}
When it comes to error handling, you have to consider both internal and external
parameters.
Internal parameters include errors that can be generated because of the bugs in
your code, or unexpected user behavior.
External errors have nothing to do with the application; rather, they are related to
parameters, which cannot be controlled. The most important one is the network
connectivity.
The most common way of doing so is simply making an HTTP request to a website that is
supposed to be up (for example, [Link] If the request succeeds, the
desktop or mobile device knows there is active connectivity. Similarly, HTML has
XMLHttpRequest for determining network availability.
HTML5, though, made it even easier and introduced a way to check whether the browser
can accept web responses. This is achieved via the navigator object:
17
Web Sockets
if ([Link]) {
alert("You are Online");
}
else {
alert("You are Offline");
}
Offline mode means that either the device is not connected or the user has selected the
offline mode from browser toolbar.
Here is how to inform the user that the network is not available and try to reconnect when
a WebSocket close event occurs:
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var wsUri = "[Link]
var output;
function init() {
output = [Link]("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
18
Web Sockets
[Link] = function(evt) {
onOpen(evt)
};
[Link] = function(evt) {
onClose(evt)
};
[Link] = function(evt) {
onError(evt)
};
}
function onOpen(evt) {
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
function onError(evt) {
writeToScreen('<span style="color:
red;">ERROR:</span> ' + [Link]);
} function doSend(message) {
writeToScreen("SENT: " + message);
[Link](message);
}
function writeToScreen(message) {
var pre = [Link]("p");
[Link] = "break-word"; [Link] = message;
[Link](pre);
}
[Link]("load", init, false);
</script>
<h2>WebSocket Test</h2>
<div id="output"></div>
</html>
19
Web Sockets
20
Web Sockets
8. Web Sockets – Send & Receive Messages
The Message event takes place usually when the server sends some data. Messages sent
by the server to the client can include plain text messages, binary data, or images.
Whenever data is sent, the onmessage function is fired.
This event acts as a client's ear to the server. Whenever the server sends data, the
onmessage event gets fired.
The following code snippet describes opening the connection of Web Socket protocol.
[Link] = function(e){
var server_message = [Link];
[Link](server_message);
}
It is also necessary to take into account what kinds of data can be transferred with the
help of Web Sockets. Web socket protocol supports text and binary data. In terms of
Javascript, text refers to as a string, while binary data is represented like ArrayBuffer.
Web sockets support only one binary format at a time. The declaration of binary data is
done explicitly as follows:
[Link]=”arrayBuffer”;
[Link]=”blob”;
Strings
Strings are considered to be useful, dealing with human readable formats such as XML
and JSON. Whenever onmessage event is raised, client needs to check the data type and
act accordingly.
The code snippet for determining the data type as String is mentioned below:
[Link]= function(event)
{
if(typeOf [Link] === String )
{
[Link](“Received data string”);
}
}
21
Web Sockets
Example
{
name: “James Devilson”,
message: “Hello World!”
}
The following code shows how to handle a JSON object and extract its properties:
[Link]= function(event)
{
if(typeOf [Link] === String )
{
//create a JSON object
var jsonObject= [Link]([Link]);
var username = [Link];
var message = [Link];
[Link](“Received data string”);
}
}
XML
Parsing in XML is not difficult, though the techniques differ from browser to browser. The
best method is to parse using third party library like jQuery.
In both XML and JSON, the server responds as a string, which is being parsed at the client
end.
ArrayBuffer
It consists of a structured binary data. The enclosed bits are given in an order so that the
position can be easily tracked. ArrayBuffers are handy to store the image files.
Receiving data using ArrayBuffers is fairly simple. The operator instanceOf is used instead
of equal operator.
22
Web Sockets
The following code shows how to handle and receive an ArrayBuffer object:
[Link]= function(event)
{
if([Link] instanceof ArrayBuffer )
{
var buffer = [Link];
[Link](“Received arraybuffer”);
}
}
Demo Application
The following program code shows how to send and receive messages using Web Sockets.
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var wsUri = "[Link]
var output;
function init() {
output = [Link]("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
[Link] = function(evt) {
onOpen(evt)
};
[Link] = function(evt) {
onMessage(evt)
};
[Link] = function(evt) {
onError(evt)
};
}
function onOpen(evt) {
writeToScreen("CONNECTED");
23
Web Sockets
doSend("WebSocket rocks");
}
function onMessage(evt) {
writeToScreen('<span style="color: blue;">RESPONSE: '
+ [Link]+'</span>'); [Link]();
}
function onError(evt) {
writeToScreen('<span style="color:
red;">ERROR:</span> ' + [Link]);
} function doSend(message) {
writeToScreen("SENT: " + message);
[Link](message);
}
function writeToScreen(message) {
var pre = [Link]("p");
[Link] = "break-word"; [Link] = message;
[Link](pre);
}
[Link]("load", init, false);
</script>
<h2>WebSocket Test</h2>
<div id="output"></div>
</html>
24
Web Sockets
9. Web Sockets – Closing a Connection
Close event marks the end of a communication between the server and the client. Closing
a connection is possible with the help of onclose event. After marking the end of
communication with the help of onclose event, no messages can be further transferred
between the server and the client. Closing the event can occur due to poor connectivity as
well.
The close() method stands for goodbye handshake. It terminates the connection and
no data can be exchanged unless the connection opens again.
Similar to the previous example, we call the close() method when the user clicks on the
second button.
It is also possible to pass the code and reason parameters we mentioned earlier as shown
below.
The following code gives a complete overview of how to close or disconnect a Web Socket
connection:
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var wsUri = "[Link]
var output;
function init() {
output = [Link]("output");
testWebSocket();
}
function testWebSocket() {
25
Web Sockets
26
Web Sockets
</script>
<h2>WebSocket Test</h2>
<div id="output"></div>
</html>
27
Web Sockets
28
Web Sockets
10. Web Socket Server – Working
A Web Socket server is a simple program, which has the ability to handle Web Socket
events and actions. It usually exposes similar methods to the Web Socket client API and
most programming languages provide an implementation. The following diagram
illustrates the communication process between a Web Socket server and a Web Socket
client, emphasizing the triggered events and actions.
The following diagram shows a Web Socket server and client event triggering:
Any valid URL can be used with the specification of a port, which was not used earlier. It
is very useful to keep a record of the connected clients, as it provides details with different
data or send different messages to each one.
29
Web Sockets
After that, we can call the Start method and wait for the clients to connect. After starting,
the server is able to accept incoming connections. In Fleck, the Start method needs a
parameter, which indicates the socket that raised the events:
[Link](socket) =>
{
});
OnOpen Event
The OnOpen event determines that a new client has requested access and performs an
initial handshake. The client should be added to the list and probably the information
should be stored related to it, such as the IP address. Fleck provides us with such
information, as well as a unique identifier for the connection.
[Link](socket) =>
{
[Link] = () =>
{
// Add the incoming connection to our list.
[Link](socket);
}
// Handle the other events here...
});
OnClose Event
The OnClose event is raised whenever a client is disconnected. The Client is removed
from the list and informs the rest of clients about the disconnection.
[Link] = () =>
{
// Remove the disconnected client from the list.
[Link](socket);
};
OnMessage Event
The OnMessage event is raised when a client sends data to the server. Inside this event
handler, the incoming message can be transmitted to the clients, or probably select only
some of them.
The process is simple. Note that this handler takes a string named message as a
parameter:
30
Web Sockets
[Link] = () =>
{
// Display the message on the console.
[Link](message);
};
Send () Method
The Send() method simply transmits the desired message to the specified client. Using
Send(), text or binary data can be stored across the clients.
[Link] = () =>
{
foreach (var client in clients)
{
// Send the message to everyone!
// Also, send the client connection's unique identifier in order
// to recognize who is who.
[Link]([Link] + " says: " + message);
}
};
31
Web Sockets
11. Web Socket as API
API – Definition
API, an abbreviation of Application Program Interface, is a set of routines, protocols, and
tools for building software applications.
The API specifies how software components should interact and APIs should be
used when programming graphical user interface (GUI) components.
A good API makes it easier to develop a program by providing all the building
blocks.
REST, which typically runs over HTTP is often used in mobile applications, social
websites, mashup tools, and automated business processes.
The REST style emphasizes that interactions between the clients and services is
enhanced by having a limited number of operations (verbs).
REST avoids ambiguity because each verb has a specific meaning (GET, POST, PUT
and DELETE)
Bidirectional
HTTP is a unidirectional protocol where the client always initiates a request. The server
processes and returns a response, and then the client consumes it. Web Socket is a bi-
directional protocol where there are no predefined message patterns such as
request/response. Either the client or the server can send a message to the other party.
Full Duplex
HTTP allows the request message to go from the client to the server and then the server
sends a response message to the client. At a given time, either the client is talking to the
server or the server is talking to the client. Web Socket allows the client and the server to
talk independent of each other.
32
Web Sockets
request/response. For Web Socket, the HTTP connection is upgraded using standard HTTP
upgrade mechanism and the client and the server communicate over that same TCP
connection for the lifecycle of Web Socket connection.
The graph given below shows the time (in milliseconds) taken to process N messages for
a constant payload size.
The graph and the table given above show that the REST overhead increases with the
number of messages. This is true because that many TCP connections need to be initiated
and terminated and that many HTTP headers need to be sent and received.
The last column particularly shows the multiplication factor for the amount of time to fulfil
a REST request.
The second graph shows the time taken to process a fixed number of messages by varying
the payload size.
33
Web Sockets
This graph shows that the incremental cost of processing the request/response for a REST
endpoint is minimal and most of the time is spent in connection initiation/termination and
honoring HTTP semantics.
Conclusion
Web Socket is a low-level protocol. Everything, including a simple request/response design
pattern, how to create/update/delete resources need, status codes etc. to be builds on top
of it. All of these are well defined for HTTP.
Web Socket is a stateful protocol whereas HTTP is a stateless protocol. Web Socket
connections can scale vertically on a single server whereas HTTP can scale horizontally.
There are some proprietary solutions for Web Socket horizontal scaling, but they are not
based on standards. HTTP comes with a lot of other goodies such as caching, routing, and
multiplexing. All of these need to be defined on top of Web Socket.
34
Web Sockets
12. Web Sockets – JavaScript Application
The following program code describes the working of a chat application using JavaScript
and Web Socket protocol.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>HTML5 Chat</title>
<body>
<section id="wrapper">
<header>
<h1>HTML5 Chat</h1>
</header>
<style>
#chat { width: 97%; }
.message { font-weight: bold; }
.message:before { content: ' '; color: #bbb; font-size: 14px; }
#log {
overflow: auto;
max-height: 300px;
list-style: none;
padding: 0;
}
#log li {
border-top: 1px solid #ccc;
margin: 0;
padding: 10px 0;
}
body {
font: normal 16px/20px "Helvetica Neue", Helvetica, sans-serif;
background: rgb(237, 237, 236);
margin: 0;
margin-top: 40px;
padding: 0;
35
Web Sockets
}
section, header {
display: block;
}
#wrapper {
width: 600px;
margin: 0 auto;
background: #fff;
border-radius: 10px;
border-top: 1px solid #fff;
padding-bottom: 16px;
}
h1 {
padding-top: 10px;
}
h2 {
font-size: 100%;
font-style: italic;
}
header,
article > * {
margin: 20px;
}
#status {
padding: 5px;
color: #fff;
background: #ccc;
}
#[Link] {
background: #c00;
}
#[Link] {
background: #0c0;
}
#[Link] {
background: #c00;
36
Web Sockets
}
#[Link] {
background: #0c0;
}
#html5badge {
margin-left: -30px;
border: 0;
}
#html5badge img {
border: 0;
}
</style>
<article>
<form onsubmit="addMessage(); return false;">
<input type="text" id="chat" placeholder="type and press enter to chat" />
</form>
<p id="status">Not connected</p>
<p>Users connected: <span id="connected">0</span></p>
<ul id="log"></ul>
</article>
<script>
connected = [Link]("connected");
log = [Link]("log");
chat = [Link]("chat");
form = [Link];
state = [Link]("status");
if ([Link] === undefined)
{
[Link] = "sockets not supported";
[Link] = "fail";
}
else
{
if (typeof [Link] != "function")
{
[Link] = function (str)
37
Web Sockets
{
return [Link](str) == 0;
};
}
[Link]("load", onLoad, false);
}
function onLoad()
{
var wsUri = "[Link]
websocket = new WebSocket(wsUri);
[Link] = function(evt) { onOpen(evt) };
[Link] = function(evt) { onClose(evt) };
[Link] = function(evt) { onMessage(evt) };
[Link] = function(evt) { onError(evt) };
}
function onOpen(evt)
{
[Link] = "success";
[Link] = "Connected to server";
}
function onClose(evt)
{
[Link] = "fail";
[Link] = "Not connected";
[Link] = "0";
}
function onMessage(evt)
{
// There are two types of messages:
// 1. a chat participant message itself
// 2. a message with a number of connected chat participants
var message = [Link];
if ([Link]("log:"))
{
message = [Link]("log:".length);
[Link] = '<li class="message">' + message + "</li>" +
[Link];
38
Web Sockets
}
else if ([Link]("connected:"))
{
message = [Link]("connected:".length);
[Link] = message;
}
}
function onError(evt)
{
[Link] = "fail";
[Link] = "Communication error";
}
function addMessage()
{
var message = [Link];
[Link] = "";
[Link](message);
}
</script>
</section>
</body>
</html>
The key features and the output of the chat application are discussed below:
To test, open the two windows with Web Socket support, type a message above and press
return. This would enable the feature of chat application.
39
Web Sockets
40
Web Sockets
41
Web Sockets
13. Web Sockets – Communicating with Server
The Web has been largely built around the request/response paradigm of HTTP. A client
loads up a web page and then nothing happens until the user clicks onto the next page.
Around 2005, AJAX started to make the web feel more dynamic. Still, all HTTP
communication is steered by the client, which requires user interaction or periodic polling
to load new data from the server.
Technologies that enable the server to send the data to a client in the very moment when
it knows that new data is available have been around for quite some time. They go by
names such as "Push" or “Comet”.
With long polling, the client opens an HTTP connection to the server, which keeps it open
until sending response. Whenever the server actually has new data, it sends the response.
Long polling and the other techniques work quite well. However, all of these share one
problem, they carry the overhead of HTTP, which does not make them well suited for low
latency applications. For example, a multiplayer shooter game in the browser or any other
online game with a real-time component.
ws is the new URL schema for WebSocket connections. There is also wss, for secure
WebSocket connection the same way https is used for secure HTTP connections.
Attaching some event handlers immediately to the connection allows you to know when
the connection is opened, received incoming messages, or there is an error.
42
Web Sockets
};
// Log messages from the server
[Link] = function (e) {
[Link]('Server: ' + [Link]);
};
// Sending String
[Link]('your message');
// Sending canvas ImageData as ArrayBuffer
var img = canvas_context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array([Link]);
for (var i = 0; i < [Link]; i++) {
binary[i] = [Link][i];
}
[Link]([Link]);
// Sending file as Blob
var file = [Link]('input[type="file"]').files[0];
[Link](file);
Equally, the server might send us messages at any time. Whenever this happens the
onmessage callback fires. The callback receives an event object and the actual message
is accessible via the data property.
WebSocket can also receive binary messages in the latest spec. Binary frames can be
received in Blob or ArrayBuffer format. To specify the format of the received binary, set
the binaryType property of WebSocket object to either 'blob' or 'arraybuffer'. The default
format is 'blob'.
43
Web Sockets
Cross-Origin Communication
Being a modern protocol, cross-origin communication is baked right into WebSocket.
WebSocket enables communication between parties on any domain. The server decides
whether to make its service available to all clients or only those that reside on a set of
well-defined domains.
Proxy Servers
Every new technology comes with a new set of problems. In the case of WebSocket it is
the compatibility with proxy servers, which mediate HTTP connections in most company
networks. The WebSocket protocol uses the HTTP upgrade system (which is normally used
for HTTP/SSL) to "upgrade" an HTTP connection to a WebSocket connection. Some proxy
servers do not like this and will drop the connection. Thus, even if a given client uses the
WebSocket protocol, it may not be possible to establish a connection. This makes the next
section even more important :)
44
Web Sockets
14. Web Sockets – Security
Protocol should be designed for security reasons. WebSocket is a brand-new protocol and
not all web browsers implement it correctly. For example, some of them still allow the mix
of HTTP and WS, although the specification implies the opposite. In this chapter, we will
discuss a few common security attacks that a user should be aware of.
Denial of Service
Denial of Service (DoS) attacks attempt to make a machine or network resource
unavailable to the users that request it. Suppose someone makes an infinite number of
requests to a web server with no or tiny time intervals. The server is not able to handle
each connection and will either stop responding or will keep responding too slowly. This
can be termed as Denial of service attack.
Denial of service is very frustrating for the end users, who could not even load a web page.
DoS attack can even apply on peer-to-peer communications, forcing the clients of a P2P
network to concurrently connect to the victim web server.
Man-in-the-middle
Let us understand this with the help of an example.
Suppose a person A is chatting with his friend B via an IM client. Some third person wants
to view the messages you exchange. So, he makes an independent connections with both
the persons. He also sends messages to person A and his friend B, as an invisible
intermediate to your communication. This is known as a man-in-the-middle attack.
From a technical aspect, the attacker intercepts a public-key message exchange and sends
the message while replacing the requested key with his own. Obviously, a solid strategy
to make the attacker's job difficult is to use SSH with WebSockets.
Mostly when exchanging critical data, prefer the WSS secure connection instead of the
unencrypted WS.
XSS
Cross-site scripting (XSS) is a vulnerability that enables attackers to inject client-side
scripts into web pages or applications. An attacker can send HTML or Javascript code using
your application hubs and let this code be executed on the clients' machines.
45
Web Sockets
An extra layer of security is added when secure WebSocket connection over SSH (or TLS)
is used.
In the WebSocket world, the main concern is about the performance of a secure
connection. Although there is still an extra TLS layer on top, the protocol itself contains
optimizations for this kind of use, furthermore, WSS works more sleekly through proxies.
Client-to-Server masking
Every message transmitted between a WebSocket server and a WebSocket client contains
a specific key, named masking key, which allows any WebSocket-compliant intermediaries
to unmask and inspect the message. If the intermediary is not WebSocket-compliant, then
the message cannot be affected. The browser that implements the WebSocket protocol
handles masking.
Security Toolbox
Finally, useful tools can be presented to investigate the flow of information between your
WebSocket clients and server, analyze the exchanged data, and identify possible risks.
46
Web Sockets
15. Web Sockets – Mobile APP
WebSocket, as the name implies, is something that uses the web. The web is usually
interwoven with browser pages because that are the primary means of displaying data
online. However, non-browser programs too, use online data transmission.
The release of the iPhone (initially) and the iPad (later) introduced a brand new world of
web interconnectivity without necessarily using a web browser. Instead, the new
smartphone and tablet devices utilized the power of native apps to offer a unique user
experience.
Smartphones have become synonymous to apps. Nowadays, there is an app for any usage,
a user can think of. Most of the apps connect to the internet in order to retrieve data,
make transactions, gather news, and so on.
It would be great to use the existing WebSocket knowledge and develop a WebSocket
client running natively on a smartphone or tablet device.
Definitely, a WebSocket web app will run on any HTML5-compliant browser, including
mobile browsers such as Safari for iOS and Chrome for mobile. Therefore, there are no
worries about compatibility issues with smartphones.
47
Web Sockets
Prerequisites
In order to develop a smartphone app, installation of development tools and SDKs are
required.
WebSockets can act as a universal hub for transmitting messages between connected
mobile and tablet clients. We can implement a native iOS application, which communicates
with a WebSocket server just like the HTML5 JavaScript client.
48