Receiving messages
Setting up
Firstly, we'll initialize our client stream
import { createClientStream } from "streamthing";
const stream = await createClientStream(process.env.SERVER_REGION);
Creating listeners
Each listener, takes an event name and a callback, which will receive the event data.
stream.receive("event", callback);
Accepting messages
To accept messages simply pass a callback, which takes a message parameter, to the receive method.
stream.receive("event", (message) => {
// Use message in any way
console.log(message);
});
Full example
import { createClientStream } from "streamthing";
async function setupStream() {
const stream = await createClientStream(process.env.SERVER_REGION);
const res = await fetch("/api/get-streamthing-token?id=" + stream.id);
const data = await res.json();
stream.authenticate(data.token);
stream.receive("event", (message) => {
console.log(message);
});
stream.disconnect(); // Make sure to disconnect in order to avoid hanging connections
}
setupStream();
Client stream
id
String. Stores the socket ID
authenticate(token)
Used to authenticate the client
receive(event, callback)
Used to receive events from the server
disconnect()
Used to disconnect from the server, to avoid hanging connections