IoT WebSocket Connection Management Algorithm for Early
Warning Earthquake Alert Applications
Ajinkya Mulay

Indian Institute of Technology,
Hyderabad
ee14btech11040@iith.ac.in

Hideya Ochiai

The University of Tokyo
ochiai@elab.ic.i.u-tokyo.ac.jp

Hiroshi Esaki

The University of Tokyo
hiroshi@wide.ad.jp

ABSTRACTIoT devices are increasingly being used in various applications andtheir field is diversifying owing to their small size. Most of the
IoT architecture takes client and server model – IoT devices areconnected to a server on the Cloud. Real time communication, especially from the server to client, is necessary when we consider theearthquake alert applications. WebSocket protocol, which has beensuccessfully used in browsers for bi-directional communication, canbe applied to such communication. However, we have to carefully
manage the loss of connection between the client and server. In thispaper, we propose a WebSocket connection management algorithm
for IoT, called reconnection with dynamic ping-pong algorithm(RDPPA), focusing on improving and adapting the WebSocket protocol for connecting IoT devices. We implemented the algorithmand carried out experiments for evaluating message delivery latency
and the amount of traffic overhead.

KEYWORDS
WebSocket, Internet of Things, Connection Management, Earthquake

1

INTRODUCTION

With the increasing role of IoT in our life, the need for real-time andbidirectional communication between IoT device and IoT server isincreasing. In the current Internet and Cloud - based architecture
multiple applications are running on the Cloud. IoT devices are
generally deployed behind a NAT or a Firewall which makes communication from the Cloud to the devices challenging. For solving
this problem, it is considered that WebSocket will provide real-timeand mutual communication[2][8].
WebSocket[10] takes a client-server model as an upgraded version of HTTP, and supports bidirectional communication. WebSocket itself is a browser based protocol originally, but because of
the bidirectional communication capability, it is also adopted in IoT
field. However, WebSocket communication is based on TCP, andsometimes the connection is lost because of the existence of middle
boxes. Such middle boxes are network address translators (NAT),

Permission to make digital or hard copies of all or part of this work for personal orclassroom use is granted without fee provided that copies are not made or distributedfor profit or commercial advantage and that copies bear this notice and the full citationon the first page. Copyrights for components of this work owned by others than ACM
must be honored. Abstracting with credit is permitted. To copy otherwise, or republish,
to post on servers or to redistribute to lists, requires prior specific permission and/or afee. Request permissions from permissions@acm.org.
UCC Companion’17, December 5–8, 2017, Austin, Texas, USA© 2017 ACM. ISBN 978-1-4503-5149-2/2/17/12. . . $15.00
DOI: https://doi.org/10.1145/3147234.3148094

Figure 1: Earthquake early warning notification over WebSocket for (1) turning kitchen stove off, (2) stopping elevators, (3) showing emergency exits, and (4) alarming people
before the S-wave, i.e., the main earthquake wave, arrives.
firewalls, Web proxy servers, and any other security managementboxes but not IP routers.
We propose a WebSocket connection management algorithm
for IoT, called reconnection with dynamic ping-pong algorithm(RDPPA), assuming to build a real-time natural disaster emergency
alert system. A server will be notified from the meteorologicalagency[14] and then if any parameter is above the disaster threshold, a message containing data about the possible disaster will besent to the IoT device over WebSocket connection. The IoT device,
will in turn take actions, e.g., (1) stopping its kitchen stove, (2) stopping its elevator, (3) lighting emergency exit light, and (4) soundingan alarm. Since all of this should occur in real-time within a second,
it is very important to deliver alert messages to the IoT devices withno loss and delay.
IoT devices normally uses narrowband, i.e., bandwidth-limited,
cellular communication to save the communication fee [1]. The
communication cost depends on the total volume of traffic consumed by the IoT devices. So, it is very important to reduce trafficIn e.g., [4–6], they discuss the use of WebSocket for remotemonitoring applications. But, they consider to use WebSocket forthe communication between a central server and a web browser,
i.e., user-interface.
[7] discusses the importance of bidirectional communication between an IoT server and a IoT device. [8] developed a tunneling ofIEEE 1888 messages over WebSocket connection in order to provide
bi-directional communication. [9] discuss the use of WebSocket forcontrolling servomotor from the server side, but it is in an educational program. All of these works do not discuss the connection
maintenance of WebSocket, which we target in this paper.

3

IOT WEBSOCKET CONNECTION
MANAGEMENT
3.1 Architecture

Figure 2: Architecture for IoT WebSocket connection management

as much as possible, while keeping connection to the WebSocket
server.
For an emergency alert system its crucial that the delay should
be really small while having the highest possible reachability. Ouralgorithm ensures to keep connection between IoT device and theserver and provide immediate alert notification from the server.
We developed a prototype system and evaluated message delivery
latency and total amount of traffic.
The paper ahead is divided into the following sections. Section
2 talks about the related work. Section 3 explains the proposedsystem model and the algorithm. Section 4 performs the evaluation.
Section 5 discusses the contribution of the algorithm and further
possibilities. Section 6 gives the conclusion of this paper.

2

RELATED WORK

Historically there have been many protocols which enable bidirectional communication and also keeps system alive for a long time.
Some of these include AJAX Long Polling and REST API. There
are also a few IoT specific protocols like CoAP, MQTT, MQTTSN besides WebSocket. But as concluded in [2], WebSocket is amuch more superior communication protocol in terms of energy
consumption, memory usage and performance. Since all three ofthese parameters are vital for IoT devices, we have decided to use it
for the emergency alert system. By [3] we can see that WebSocket
outperforms REST API in terms of energy consumption and latency.

Fig 2 shows the architecture for IoT WebSocket connection management. It consists of IoT WebSocket server and IoT device. These
two components are connected over a WebSocket channel, which
communication is initiated from the IoT device. There potentiallyexists middle boxes (e.g., NAT, firewall, proxy) that may kill the TCP
connection intentionally without notifying to the server and thedevice. The server and device exchange special messages, labelled
as SPI, CPO, CPI and SPO in the figure, to check and keep the statusof connection. The alert generator of the server receives externalsignal (e.g., the beginning of earthquake signal) and sends an alert
signal to the affected IoT devices. The IoT devices can take actions
to make our life safe, such as stopping elevators before the primaryhuge earthquake waves arrive.
For managing the WebSocket connection, we propose a reconnection with dynamic ping-pong algorithm (RDPPA). In the algorithm,
server and device exchange, server ping (SPI), client pong (CPO) in
response to SPI, client ping (CPI), and server pong (SPO) in response
to CPI. Pings from client and server are issued with dynamic changing interval discovering the existence of the middle boxes. We here
describe RDPPA server side algorithm and client side algorithm.

3.2

RDPPA Server SideWe will be referring to the Algorithm 1 in this section. On theserver side, the inputs to the RDPPA Algorithm are Port Number(Serverpor t ) for webserver to start the connection on and the Server
Path (Serverpath ) for one client. The server starts a webserver
on Serverpor t and then handles the incoming connections with
the Connection Handle Function on its current IP address withthe path specified by Serverpath . The other inputs are timeinit ,time f ix ed and delayf ix ed . Note that whenever a new connection
joins the HTTP connection is upgraded to a WebSocket connection
by an Upgrade function. After that the server algorithm proceeds
as shown in Algorithm 1.
Whenever a new client initiates connection with the server,
Connection Handle Function handles them. This function has
3 threads - (1) Receiving Thread, (2) Data sending Thread and (3)Ping-Pong Handling Thread.
3.2.1 Receiving Thread. When the client starts it sends introductory data which includes the Device Type, ID and Periodic TimeInterval (PTI). The device type and ID helps the server differentiate

Algorithm 1 RDPPA Server Side
1: Inputs:

Serverpor t , Serverpat h , timeinit , time f ix ed ,delayf ix ed
2: Connection Handle Function:
3: Initialisation:

4: currentTime, previousTime, sendTime, strikes = 0
5: waitingTime = delay f ix ed
6: PTI = timeinit

7: Receiving Thread:
8: while true do

if Unique Introductory Data received from client thenStore client device type and ID
11:
Update PTI to client PTI
12:
else if Repeated Introductory Data then13:
Block device and disconnect
14:
else if CPI received from client then15:
Send SPO back to client
16:
else if CPO received from client then17:
PTI+=t f ix ed
18:
strikes = 0
19:
end if
20: end while
21: Data Sending Thread:
22: Send any alert/data to client if available
23: Ping-Pong Handling Thread:
24: while true do
25:
currentTime = time.now()26:
if (currentTime - sendTime) ≥ waitingTime AND (SPI sent)
AND (CPO NOT received) then27:
Quick Recovery Mode:28:
if strikes ≤ 3 then29:
strikes++
30:
else
31:
Close connection to client
32:
PTI/=233:
end if34:
else if (currentTime - previousTime) ≥ PTI OR (strikes ≥1) then35:
Send SPI to client
36:
sendTime = time.now()37:
end if
38: end while
39: Main:
40: Listen and run server on Server por t at Server pat h with handle(Connection Handle Function)
9:10:

the incoming clients and avoid repetitions. The PTI is used forsending pings. The Receiving Thread handles incoming CPI andCPO and sends back SPO in response to the CPI. All these terms
and their usage will be explained in the Ping-Pong Thread section.
3.2.2 Data Sending Thread. Whenever the server receives acommand to send an Alert or some kind of data to the client, thisthread sends it.
3.2.3 Ping-Pong Thread. As the main aim of this algorithm is tomake sure the TCP connection under the WebSocket is not killed

by intermediate boxes we have implemented a Ping-Pong system.
To make sure the client-server connection is alive both the server
and the client periodically check the connection at intervals of PTI,
by sending pings and waiting for a pong to return back in under thewaiting time of delayf ix ed . The PTI is initialised with the amountof timeinit . Now since these ping pong will add traffic overhead
to the data messages we have implemented a dynamic ping-pongsystem. Whenever a ping sent gets the pong response withing thedelayf ix ed time interval, we update the PTI by adding time f ix ed
to the current PTI. This increases the delay between consecutive
successful pings which reduces the traffic overhead over time.
If on the other hand, the pong response to the ping fails to reach
within the delayf ix ed time interval we resort to Quick Recovery
Mode. In this mode we send a pings until the device responds witha pong under the delayf ix ed time interval or 3 pings receive nopong response. If a response is received the connection is assumed
to be alive and continues operating fine while if no response isreceived the server closes the connection.

3.3

RDPPA Client Side

Here we are going to refer to Algorithm 2. Initially the server isassumed to powered on and waiting for new client connections.
The client then is powered on and the inputs to it are the Server
IP Address (Server addr ), Server Port (Serverpor t ), Webserver Host(W Shost ), Webserver Path (W Spath ), TCP client object (TCPclient ),Web Socket Client Object (W Sclient ) and knows own MAC Address.
The other inputs are delayf ix ed , timeinit and time f ix ed . The client
initially turns on its Serial Monitor and then obtains IP addressby using its own MAC address and DHCP on the network its connected to. After that, the client algorithm proceeds as described in
Algorithm 2. Here there are 2 parts in the Client Algorithm - (1)Handshake Setup, (2) Main Loop.
3.3.1 Handshake Setup. Initially the Handshake Setup Function is executed. The TCPclient object sends a connection request
on the port and path which the server is listening on via the network (Wi-Fi, Ethernet or cellular) the client is accessing. If theconnection is not successful, then the client continues to try connecting periodically with a delay of 2 seconds until successful. Once
successful the client sets the WebSocket host and the WebSocket
Path and proceeds to initiate a WebSocket handshake. Again if
the handshake is unsuccessful, then the client continues to try thehandshake with a delay of 2 seconds until connected. Once thehandshake is completed the client sends introductory data to serverand breaks out of the Handshake Setup Loop and proceeds to theMain Loop.
3.3.2 Main Loop. On every loop the TCPclient object checks
whether the client is connected. If it detects it is not connected thenit closes the current connection and proceeds to retry handshakewith the current PTI. Note that this method is unable to detect the
TCP kills done by the intermediate boxes and works only when
the underlying TCP connection is alive. If the TCPclient object
identifies the connection is alive then the Main Loop is able toreceive Alerts sent by the server as well as SPI and SPO. In response
to SPI, the Main Loop sends back CPO. If SPO is received under thewaiting time of delayf ix ed time interval then the PTI is updated by

Algorithm 2 RDPPA Client Side
Inputs: TCPcl ient , W Scl ient , Server addr , Serverpor t ,W Shost , W Spat h , delayf ix ed , timeinit , time f ix ed
2: Handshake Setup Function: (PTI)
while true do
4:currentTime, previousTime, sendTime, strikes = 0
waitingTime = delayf ix ed
6:
if TCPcl ient .connect(Server addr , Serverpor t ) is successful
then
Set W Scl ient host (W Shost ) and path (W Spat h ) parameters
8:
if W Scl ient handshake is successful thenSend PTI to server and BREAK from loop10:else
Retry handshake
12:
Delay(2 seconds)
end if
14:
else if TCPcl ient .connect(Server addr , Serverpor t ) is unsuccessful thenRetry connection
16:
Delay(2 seconds)
end if
18: end while
Main:
20: PTI = timeinit
Call Handshake Setup (PTI)
22: while true do
if TCPcl ient is connected then24:
currentTime = time.now()
if Alert Received from server then26:
Print out data and trigger hardware
else if SPI received from server then28:
Send CPO to server
else if SPO received from server then30:
PTI+=time f ix ed
strikes = 0
32:
end ifif (currentTime - sendTime) ≥ waitingTime AND (CPIsent) AND (CPO NOT Received) then
34:
Quick Recovery Mode:
if strikes ≤ 3 then36:
strikes++
else if strikes > 3 then38:
PTI/=2
Stop TCPcl ient and Re-initiate Handshake Setup
(PTI)
40:
end ifelse if (currentTime - previousTime) ≥ PTI OR (strikes≥ 1) then42:
Send CPI
sendTime = time.now()44:
end ifelse if TCPcl ient then46:
PTI/=2
Stop TCPcl ient and Re-initiate Handshake Setup (PTI)48:
end ifend while

Figure 3: Configurations for measuring message delivery latency and WebSocket traffic
adding time f ix ed to the current PTI. The PTI has been initialisedwith the value of timeinit . If however the SPO is not received under
the delayf ix ed time interval then the Client goes into the Quick
Recovery Mode just like the Server. It then just like the server
proceeds to send CPI to server until it receives an SPO or it hascompleted 3 tries.
If the SPO is received within this time, then the connection isassumed to be alive and everything continues to function normally.
On the other hand if the SPO is not received then the client closes
the connection and proceeds to re-initiate Handshake Setup withthe current PTI.

4

EVALUATION

We implemented RDPPA onto our prototype system and evaluatedthe latency of alert message delivery and the amount of total traffic.
As a reference, we compared RDPPA with a simple re-connection
algorithm (SRA). SRA does not exchange ping-pong messages but
simply re-initiates a WebSocket connection from a client side when
the client detects the loss of the TCP session.

4.1

Experiment Setting

Fig. 3 shows our experiment setting. We implemented IoT WebSocket server onto a laptop computer (DELL Inspiron 14, 5000) with
Golang Gorilla WebSocket library[11] in golang. We implemented
IoT devices onto an Arduino Mega compatible board with ArduinoWebSocket library[12]. We have prepared other two Arduinos formeasuring latencies of the alert message from the server to theclient. For Golang to Arduino Serial Communication Tarm Serial
library was used. [13] As for the network, we prepared three typesof networks as follows:• Case 1 (Ethernet): Direct connection between client andserver over Ethernet, i.e., on an IP network segment. There
were no middle boxes.
• Case 2 (Wi-Fi): Connection over our university campus
network. There was a NAT between client and server, butTable 1: Average message delivery latency. 3G case hasachieved almost same performance as Wi-Fi case. As for
SRA for 3G, data was not available because of the failure ofmessage delivery.
Test Network (applied Algorithm)

Average Delay [ms]Ethernet (SRA)

0.010

Ethernet (RDPPA)

0.011

Wi-Fi (SRA)

6.05

Wi-Fi (RDPPA)

50

0

51

2923

Ethernet(RDPPA)

50

0

358

25023

7.04

3G (SRA)N/A

Wi-Fi (SRA)

50

0

51

3570

3G (RDPPA)

7.89

Wi-Fi (RDPPA)

50

0

358

25023

3G (SRA)

50

49

51

130

3G (RDPPA)

50

0

730

61306

Message Delivery Latency

According to the Block diagram in Fig. 2, a common server issending the exact same message to two Arduinos. One Arduino isconnected to the server via one of the 3 MAC Layers (either Wi-Fi,
Ethernet or 3G Cellular) over a websocket and the other is directly
connected to the server via a wired serial link. Since the wired
serial link has the least possible delay, we are comparing it withthe websocket link to compare the timings of both.
Now to synchronise the timings for two independent Arduinos,
we need to have a common clock. So, we have placed a Synchronising Arduino which is wired to the output ports of both the Arduinos.
Whenever either of the Arduino receives any server message, that
Arduino changes the state of its output PIN as high for a small
time duration of 10 milliseconds. The synchronising Arduino isconstantly monitoring the states of the output pins of the 2 Arduino
through the wired link and every time the state is changed, thelocal clock timing is noted by the Synchronising Arduino. Whenthe state of the other Arduino changes as well, the time differenceis calculated and printed to the Serial console of the synchronising
Arduino. The delay calculated has a precision of 4 microseconds,
since that is the maximum precision offered by Arduino.

4.3

Test Network Messages Messages Packets Bytes(applied Algo- Sent
Dropped (Total) (Total)
rithm)
Ethernet (SRA)

this NAT is configured not to kill TCP connection for 7
days.
• Case 3 (3G): Connection over a carrier network. There aresupposed to be several black-boxed middle boxes between
client and server.
In each of these networks we tested the websocket connection
between the Arduino, i.e., IoT devices, and the IoT WebSocket server
on SRA and RDPPA.

4.2

Table 2: Traffic volume measured by the experiment.
RDPPA generated much larger traffic volume than SRA did.
In 3G case, the WebSocket connection were kept available
with RDPPA, but it failed with SRA.

Traffic Overhead

While designing a reliable algorithm, a certain overhead is incurredin the form of data exchanged which leads to latency degradation.
Considering that IoT devices might not have high speed lines dedicated for transmission especially in cellular communication, it
becomes vital that the overhead occurred is affordable and useful
in decreasing net delay while increasing the message accuracy.
In the basic algorithm of just re-connection we do not have theping pong messages while in the advanced algorithm we have thosemessages too. This difference in the traffic overhead is what we wantto calculate along. This is done by using ’tcpdump’ command andthen analysing the obtained file using inbuilt filters in Wireshark.
The graphs for each of the networks have been presented below.
To take this into account we are sending the necessary periodic connection stay awake messages with a additive increase /multiplicative decrease algorithm.

4.4

Application of Earthquake Alarm

The architecture for deploying a real-time earthquake alert system
is very similar to the one described in Fig. 2. Our prototype fordemonstration setup is described in Fig. 5. As seen in the Fig. 5, theserver is supposed to receive a notification of an imminent earthquake via a government agency/website like Japan Meteorological
Agency. The moment this alert is received by the server, the server
passes on this alert to the Arduino clients connected to it over cellular network or Wi-Fi via WebSocket protocol. In the alert sentfrom the server to the Arduino clients, the server specifies what
hardware functions it wants the client to perform. The Arduino
which is connected to devices like LEDs, speakers or even highpowered machines can then turn on LEDs or sound an alarm oreven cut off power to the high powered machines. Such a system isvery much crucial to avoid accidents in case of an earthquake.
An Earthquake Early Warning System (EEW) have already been
implemented in Japan [14]. Such a system, tracks the P-wave which
are the preliminary tremors of the earthquake. Once these aredetected it estimates the incoming seismic intensities and the arrival
time of the S-wave or the principal motion of the earthquake. This
intermediate time is very crucial to provide time for evacuation,
stopping elevators and even the high-speed bullet trains. All these
activities can be carried out by the system suggested in Fig. 2 using
the low-latency WebSocket IoT Network. For practical demo, we
carried out the blinking of an LED and stopping a motor using
RDPPA over 3G network.

Figure 4: Cumulative distribution function (CDF) of message delivery latency for (1) Ethernet, (2) Wi-Fi and (3) 3G. (* - For 3G,
there is no CDF for SRA, because of the failure of alert message delivery.)

6

CONCLUSION

In this paper, we proposed a WebSocket connection management
algorithm for IoT, called reconnection with dynamic ping-pongalgorithm (RDPPA), assuming to build a real-time natural disasteremergency alert system.
The results of our experiments indicate that RDPPA performs
efficiently on several network cases regarding to the amount of total
traffic required and message delivery latency with keeping connections alive. We demonstrated that WebSocket is useful for criticalapplications such as early-warning earthquake alert applications.

REFERENCES

Figure 5: Earthquake alarm system implementation. Alert
messages are delivered over the IoT WebSocket connections.
A LED light and a power motor are controlled.

5

DISCUSSION

In the current system we have not used the secure version of WebSocket Protocol. We have used ’ws’ protocol which is similar to
HTTP and not ’wss’ which is more similar to HTTPS. If used withthe secure version the delay measurement might change due tosecurity overhead. This is because we are focusing only on thecommunication parameters of the network and not the security.
Currently in our earthquake alert system, we are broadcasting
the same messages to all the clients from the server since they
are in a similar geographical area. But, if we consider a realistic
scenario for earthquake, the alert level will be different in different
regions. This can be taken care of by transmitting the latitude andlongitude from the IoT devices. Since, these IoT devices will bestationary when deployed, we can set the location inside the clientand it can be requested at any time. Or else, it may be acquiredby triangulation which will take up some more processing power.
Either ways, the location will be sent to the server on request andthe server according to its data and region classification will send
the appropriate alerts to the IoT devices.

[1] Narrowband IoT (NB-IoT), https://www.u-blox.com/en/narrowband-iot-nb-iot[2] Dae-Hyeok Mun, Minh Le Dinh, and Young-Woo Kwon. An Assessment of Internetof Things Protocols for Resource-Constrained Applications. In IEEE COMPSAC, 2016.
[3] Volker Herwig, Ren Fischer and Peter Braun. Assessment of REST and Websocket
in regards to their Energy Consumption for mobile Applications In IEEE IDAACS,
2015.
[4] A. Hashibuan, M. Musrdi, E. Y. Syamsuddin, and M. A. Rosidi. Design and Implementation of Modular Home Automation Based on Wireless Network, REST API, and
WebSocket. In IEEE ISPACS, 2015.
[5] L. Zhang and Xiaoxiao Shen. Research and Development of Real-time Monitoring
System Based on WebSocket Technology. In IEEE MEC, 2013.
[6] Z. B. Babovic, J. Protic, and V. Milutinovic. Web Performance Evaluation for Internetof Things Applications. IEEE Access, vol. 4, pages 6974 - 6992, 2016.
[7] C. Doukas, L. Capra, F. Antonelli, E. Jaupaj, A. Tamilin, and I. Carreras. Providing
Generic Support for IoT and M2M for Mobile Devices. In IEEE RIVF, 2015.
[8] Y. Tarutani, S. Murata, K. Matsuda, and M. Matsuoka. IEEE1888 over WebSocket
for communicating across a network boundary. In IEEE COMPSAC, 2016.
[9] G. C. Fernandez, E. S. Ruiz, M. C. Gil, and F. M. Perez. From RGB led laboratory to
servomoter control with websockets and IoT as educational tool. In IEEE REV, 2015.
[10] The WebSocket Protocol., https://tools.ietf.org/html/rfc6455[11] Gorilla Websocket Library - A Go implementation of the Websocket protocol. Retrieved from https://github.com/gorilla/websocket[12] Brandenhall Arduino-Websocket Library - Simple Library that implements WebSocket client and server running on Arduino. Retrieved fromhttps://github.com/brandenhall/Arduino-Websocket[13] Tarm Serial Library - Go package to allow you to read and write from the serial
port as a stream of bytes. Retrieved from https://github.com/tarm/serial[14] Earthquake Early Warning System, http://www.jma.go.jp/jma/en/Activities/eew.html