Spaces:
Sleeping
Sleeping
const API_URL = 'http://localhost:8080'; | |
export const establishPeerConnection = async (token: string): Promise<{ pc: RTCPeerConnection, dc: RTCDataChannel }> => { | |
const pc = new RTCPeerConnection(); | |
const dc = pc.createDataChannel('chat'); | |
dc.onopen = () => console.log('Data channel open'); | |
dc.onmessage = (event) => console.log('Received message:', event.data); | |
const offer = await pc.createOffer(); | |
await pc.setLocalDescription(offer); | |
const response = await fetch(`${API_URL}/webrtc/offer`, { | |
method: 'POST', | |
headers: { | |
'Authorization': `Bearer ${token}`, | |
'Content-Type': 'application/json', | |
}, | |
body: JSON.stringify({ | |
sdp: pc.localDescription?.sdp, | |
type: pc.localDescription?.type, | |
}), | |
}); | |
if (!response.ok) { | |
throw new Error('Failed to establish WebRTC connection'); | |
} | |
const data = await response.json(); | |
const remoteDesc = new RTCSessionDescription(data); | |
await pc.setRemoteDescription(remoteDesc); | |
pc.onicecandidate = async (event) => { | |
if (event.candidate) { | |
await fetch(`${API_URL}/webrtc/ice-candidate`, { | |
method: 'POST', | |
headers: { | |
'Authorization': `Bearer ${token}`, | |
'Content-Type': 'application/json', | |
}, | |
body: JSON.stringify(event.candidate), | |
}); | |
} | |
}; | |
return { pc, dc }; | |
}; |