Developer Documentation
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Start an Event Stream

Once you have connected and authenticated to the RealTime API, you’ll probably want to do something useful with it. In this example, we’re going to enable the event stream for your user. When this stream is active, you’ll receive numerous events of all kinds that pertain to your user: Incoming call notifications, outgoing call notifications, call progress events, incoming and outgoing message events, status updates, etc…

client.onmessage = function(event)
{
   const message = JSON.parse(event.data);
   if (message.type == "authresponse" && message.success === true)
   {
      console.log("Yay! We are authenticated!");
   }
   else if (message.type == "authresponse" && message.success === false)
   {
      console.log("We are not authenticated :(");
   }
   else if (message.type == "startusereventresponse" && message.success === true)
   {
      console.log("User event stream started!");
   }
   else if (message.type == "startusereventresponse" && message.success === false)
   {
      console.log("Could not start user event stream.");
      console.log(message);
   }
   // We received an event of type 'userevent'. Display it on the console.
   if (message.type == "userevent")
   {
      console.log(message);
   }
};

client.onopen = (event) =>
{
   client.send(JSON.stringify({"type":"authrequest", "token":"c04c7ff7-5fa1-48fb-aa2a-bcf97a6b8a79"}));
};

Now that we’ve added our handlers for the user event stream, we need to send the command to activate it. To be honest, using a timer here is a bit of a hack and we don’t recommend you actually do this in production. We’re waiting 5 seconds for the server to make sure we’ve authenticated, then we will send our request to start the user stream.

In production, you should wait until you receive the “authresponse” event, then start the stream there.

client.onopen = (event) =>
{
   client.send(JSON.stringify({"type":"authrequest", "token":"c04c7ff7-5fa1-48fb-aa2a-bcf97a6b8a79"}));

   setTimeout(5000, () =>
   {
      client.send(JSON.stringify({"type":"startusereventrequest"}));
   });
};

Test out your event stream by texting your user’s number, or calling it. You’ll see various events show up on the console as they happen in real time.