< Blogs
Elliott

Elliott

June 21, 2022

How-Tos: Using WebSockets

Live-streaming data is only a handshake away.

Websockets allow you to maintain a stream of data in real-time whenever you need it! You can use it to build some really amazing features ranging from simple heart rate streaming to your phone during a run to complex robotic hand gestures to the other side of the world so that a robotic hand on the other side mimics your hand gestures.

Definitions

Websocket connections are quite simple in a top-level sense: You initiate a connection with a WebSocket server, and upon connection, you might be asked for verification for connection. This part initiates a handshake with the server. After that, you simply maintain the server connection and start sending/receiving live streaming data!

To maintain the server connection, it is often needed to perform a sort of "connection check" every once in a while. Typically this is done byPING PONG. You ping the server, and the server responds with a pong signifying the connection is still alive.

WebSocket Connection

Example Usage

Each WebSocket server has its own protocol. We here at Terra created a very simple WebSocket server to stream data from a user's device to our developers.

Let's assume you are a developer using Terra. You wish to connect to our WebSocket server to see real-time data from your users.

There are a few things we must do:

  • Initiate the connection
  • Send a verification (we use tokens)
  • Maintain a heartbeat (The ping/pong we use to keep the connection in check)

For this example, we will be using Javascript's ‘ws' library. However, implementation is similar for other languages!

Let us also assume you have generated the token. If you do not know how to please check out our blog on how to use a REST API!

First, let us maintain the connection and perform the handshake:

The code above initializes a function for keeping a WebSocket connection. On line 6 it initiates a connection to the WebSocket server.

The ‘ws' library allows us to implement EventListener's through the addEventListener function.

  • open tells the connection what should happen upon connection. Right now we simply print Connection Established
  • close and error currently also only prints that the connection either closed or errored. On close, there's usually a reason why it closed, and on error, there usually is an error code telling you what was the cause.
  • message is the main part. You can do something on a message sent to you. Terra's websocket messages always come with an op field signifying an Opcode. Opcode 2 is "HELLO". Upon initialising a connection, this sends you a payload as such: {"op":2, "d":{"heartbeat_interval": 40000}}. This message essentially tells you to send a ping (in this case a heart beat), every 40000 milliseconds. This is what the heartBeat() function does. The setInterval() function allows you to periodically call the function at a set interval. Opcode 1 means "Heartbeat acknowledged". This means that the server knows you are still connected and would not close your connection. Finally, Opcode 3 means "VERIFY". You send this payload to the server to verify your status.
  • Any other messages, are simply printed.

Next, we can run the function, and see what happens:

Connection Established
↓  {"op":2,"d":{"heartbeat_interval":40000}}
↑  {"op":0}
↑  {"op":3,"d":{"token":"dGVzdGluZ0VsbGlvdHQ.MU1fASa1nR9EpQWQx67xIN7veTFKFwudaB4HbN4kw9A","type":1}}
↓  {"op":1}
↓  {"op":4}
↑  {"op":0}
↓  {"op":1}
↓  {"op":5,"d":{"ts":"2022-06-01T14:47:08.055Z","val":86.0},"uid":"100b370c-d2be-42a2-b757-01fc85c41031","seq":12254,"t":"HEART_RATE"}
↓  {"op":5,"d":{"ts":"2022-06-01T14:47:08.701Z","val":87.0},"uid":"100b370c-d2be-42a2-b757-01fc85c41031","seq":12255,"t":"HEART_RATE"}
↓  {"op":5,"d":{"ts":"2022-06-01T14:47:09.698Z","val":86.0},"uid":"100b370c-d2be-42a2-b757-01fc85c41031","seq":12256,"t":"HEART_RATE"}
↓  {"op":5,"d":{"ts":"2022-06-01T14:47:11.041Z","val":86.0},"uid":"100b370c-d2be-42a2-b757-01fc85c41031","seq":12257,"t":"HEART_RATE"}
↓  {"op":5,"d":{"ts":"2022-06-01T14:47:12.049Z","val":86.0},"uid":"100b370c-d2be-42a2-b757-01fc85c41031","seq":12258,"t":"HEART_RATE"}

We can break the messages down:

  • An initial Hello from the server with Opcode 2 followed by the script sending an Opcode 3 with the verification payload. The server then sends back an Opcode 4 meaning "READY".
  • The 'Opcode 0 and Opcode 1 to and from the server is simply the heart beating
  • Then there are many Opcode 5 messages that contain data for a user with uid and their "HEART_RATE" values.

Go wild

The messages in these WebSocket connections can be completely arbitrary. As said before, each WebSocket server has its own protocol and may not adhere to the same one. However, the idea is always the same: you initiate the connection, complete the handshake, and do something "on message, on open, and on close". These are usually implemented within an external library that you can use. Similar to the "ws" library from javascript, there's also "websockets" library on python, URLSessionWebSocketTask object in swift, and "okhttp3" on java to create WebSocket connections.

Keeping this same structure in mind, you should be able to connect to any WebSocket server as you wish (as long as you follow their structure). Other than the current example given, you can also send messages through WebSockets in a chat room, get live social media feeds, get real-time financial stock data, or even real-time sports updates!

More Topics

All Blogs
Team Spotlight
Startup Spotlight
How To
Blog
Podcast
Product Updates
Wearables
See All >
CEO and Founder of Prenuvo - Andrew Lacy

CEO and Founder of Prenuvo - Andrew Lacy

In this podcast with Kyriakos the CEO of Terra, Andrew Lacy shares his journey with Prenuvo which began from a personal health crisis.

Terra APITerra API
August 28, 2024
MedHacks: Using Wearables To Predict Heart Attacks

MedHacks: Using Wearables To Predict Heart Attacks

A few weeks ago we met Vishal, a recent engineering graduate who wanted to use Terra API as part of his MedHacks hackathon project, Cardio Clarity.

Gursukh SembiGursukh Sembi
August 19, 2024
July 2024 updates

July 2024 updates

Teams API adds Kinexon integration & new webhooks. Terra Health Scores now include Respiratory & Stress metrics. Eight Sleep integration returns with enhanced data.

Alex VenetidisAlex Venetidis
August 2, 2024
Vice President of Teamworks - Sean Harrington

Vice President of Teamworks - Sean Harrington

In this podcast with Kyriakos the CEO of Terra, Sean Harrington shares his journey from founding NoteMeal to becoming the VP of Teamworks.

Terra APITerra API
August 2, 2024
Chief Digital Product Officer of Les Mills - Amber Taylor

Chief Digital Product Officer of Les Mills - Amber Taylor

In this podcast with Kyriakos the CEO of Terra, Amber Taylor shares her journey from childhood running to her leadership role at Nike and navigating cultural differences.

Terra APITerra API
August 2, 2024
next ventures
pioneer fund
samsung next
y combinator
general catalyst

Cookie Preferences

Essential CookiesAlways On
Advertisement Cookies
Analytics Cookies

Crunch Time: Embrace the Cookie Monster Within!

We use cookies to enhance your browsing experience and analyse our traffic. By clicking “Accept All”, you consent to our use of cookies according to our Cookie Policy. You can change your mind any time by visiting out cookie policy.