Skip to content

Commit fcad243

Browse files
authored
Add experimental method to prepare connection in order to speed up subsequent ws connection (#469)
* add method to prepare connection for speeding up subsequent first connection attempt * changeset * update comment * mark as experimental * update changeset
1 parent 951a07c commit fcad243

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

.changeset/smooth-dots-breathe.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'livekit-client': patch
3+
---
4+
5+
Add experimental method to prepare connection for speeding up subsequent first connection attempt

example/sample.ts

+7-1
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,11 @@ const appActions = {
9898
): Promise<Room | undefined> => {
9999
const room = new Room(roomOptions);
100100

101+
startTime = Date.now();
102+
await room.prepareConnection(url);
103+
const prewarmTime = Date.now() - startTime;
104+
appendLog(`prewarmed connection in ${prewarmTime}ms`);
105+
101106
room
102107
.on(RoomEvent.ParticipantConnected, participantConnected)
103108
.on(RoomEvent.ParticipantDisconnected, participantDisconnected)
@@ -149,6 +154,8 @@ const appActions = {
149154
renderScreenShare(room);
150155
})
151156
.on(RoomEvent.SignalConnected, async () => {
157+
const signalConnectionTime = Date.now() - startTime;
158+
appendLog(`signal connection established in ${signalConnectionTime}ms`);
152159
if (shouldPublish) {
153160
await Promise.all([
154161
room.localParticipant.setCameraEnabled(true),
@@ -159,7 +166,6 @@ const appActions = {
159166
});
160167

161168
try {
162-
startTime = Date.now();
163169
await room.connect(url, token, connectOptions);
164170
const elapsed = Date.now() - startTime;
165171
appendLog(

src/room/Room.ts

+12
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,18 @@ class Room extends (EventEmitter as new () => TypedEmitter<RoomEventCallbacks>)
218218
return DeviceManager.getInstance().getDevices(kind, requestPermissions);
219219
}
220220

221+
/**
222+
* prepares the connection to the livekit server by sending a HEAD request in order to
223+
* 1. speed up DNS resolution
224+
* 2. speed up TLS setup
225+
* on the actual connection request
226+
* throws an error if server is not reachable after the request timeout
227+
* @experimental
228+
*/
229+
async prepareConnection(url: string) {
230+
await fetch(`http${url.substring(2)}`, { method: 'HEAD' });
231+
}
232+
221233
connect = (url: string, token: string, opts?: RoomConnectOptions): Promise<void> => {
222234
if (this.state === ConnectionState.Connected) {
223235
// when the state is reconnecting or connected, this function returns immediately

0 commit comments

Comments
 (0)