Last active
January 18, 2025 07:44
-
-
Save tyohan/51caa8ae22ce43ea88bf471915ba6389 to your computer and use it in GitHub Desktop.
Inlive chat example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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