• Unified API
  • Mobile SDK
  • Connection Widget
  • Streaming
  • Lab Reports API
  • Graph API
  • Health Scores
  • Health Rewards
  • Planned Workouts
  • Lab Testing
  • AI Interface
  • Enterprise
  • Insurance
  • Integrations
  • Research
  • Podcast
  • Blog
  • Reports
  • Events
  • Documentation
  • Community
  • Example apps
  • Wearable Data
  • About
  • Customers
  • Partners
  • Careers
  • Support
  • Pricing
Terra
Pricing
Become an integrationGet started
next ventures
pioneer fund
samsung next
y combinator
general catalyst

The world's best health apps run on Terra data

Get started
ProductsIntegrationsAI InterfaceAuthenticationMobile DevelopmentDocumentationGraphAPI
DocumentationAPISDKQuickstart
CommunityBlogResearchCommunityPodcastAuthorsGithub
CompanyAboutCareersCustomersBecome an IntegrationCookies PolicyGDPRPrivacy PolicyTerms of Purchase
© Terra API. 2026 — All rights reserved.

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.

Cookies Policy
All articles

How To

How-Tos: Using WebSockets

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 i


Elliott Yu
Elliott Yu

21 June 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!

Get the latest Terra Research reports and insights every week as soon as they're published.

By continuing, I agree to the Privacy Policy and Terms of Service.

Previous
Next

Continue reading

  • Health Data Residency: EU by Default, Optional US Cluster

    Here's our guide to which region your users' health data is processed and stored in, why we default to the EU, and when it makes sense to add a US cluster.

    21 September 2026

  • The complete guide: How the new Google Health API works

    Google Health API replaces the Fitbit Web API. This is the field guide with code, schemas, and a migration playbook to help you understand where Google Health is heading.

    18 May 2026

  • 5 Lessons for Standing Out at HLTH

    5 lessons from team Terra API for making a lasting impact at HLTH: from engaging senses to building real touch points, here’s what we learned from the HLTH event.

    5 December 2024