Skip to content

Instantly share code, notes, and snippets.

@tyohan
Last active January 18, 2025 07:44
Show Gist options
  • Save tyohan/51caa8ae22ce43ea88bf471915ba6389 to your computer and use it in GitHub Desktop.
Save tyohan/51caa8ae22ce43ea88bf471915ba6389 to your computer and use it in GitHub Desktop.
Inlive chat example
import { Room, RoomEvent, createAuth } from '@inlivedev/inlive-js-sdk';
const auth = await createAuth({
apiKey: 'YOUR_API_KEY',
expirySeconds: 3600,
});
const room = Room();
room.setAuth(auth);
const newRoom = await room.createRoom('a new room', 'custom-id');
room.createDataChannel(roomId: newRoom.data.roomId, name: "chat")
const client = await room.createClient(newRoom.data.roomId);
const peer = await room.createPeer(newRoom.data.roomId, client.data.clientId);
let chatChannel = null;
const peerConnection = peer.getPeerConnection();
// when iceConnectionState is connected, it indicates the connection is established
peerConnection.addEventListener('iceconnectionstatechange', function () {
console.log(peerConnection.iceConnectionState);
});
peerConnection.addEventListener('datachannel', (event) => {
if (event.channel.label === 'chat') {
chatChannel = event.channel;
chatChannel.onmessage = (event) => {
// handle chat message
let receivedString = '';
if (event.data instanceof ArrayBuffer) {
// If it's an ArrayBuffer, convert it to a string
const decoder = new TextDecoder(); // Use TextDecoder to decode
receivedString = decoder.decode(event.data);
} else if (typeof event.data === 'string') {
// If it's already a string, just use it directly
console.log("Received string:", event.data);
receivedString = event.data;
} else {
console.log("Received data of type:", typeof event.data);
}
if (receivedString !== '') {
data = JSON.parse(receivedString);
// handle chat messagehere
}
}
}
});
function sendMessage(message) {
if (chatChannel) {
chatChannel.send(JSON.stringify(message));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment