ghostream/web/static/js/modules/websocket.js

64 lines
2.0 KiB
JavaScript
Raw Normal View History

2020-10-20 19:29:41 +00:00
/**
* GsWebSocket to do Ghostream signalling
*/
export class GsWebSocket {
constructor() {
const protocol = (window.location.protocol === "https:") ? "wss://" : "ws://";
this.url = protocol + window.location.host + "/_ws/";
}
_open() {
this.socket = new WebSocket(this.url);
}
/**
* Open websocket.
* @param {Function} openCallback Function called when connection is established.
* @param {Function} closeCallback Function called when connection is lost.
*/
2020-10-20 19:45:26 +00:00
open() {
2020-10-20 19:29:41 +00:00
this._open();
2020-10-20 19:45:26 +00:00
this.socket.addEventListener("open", () => {
2020-10-20 19:29:41 +00:00
console.log("WebSocket opened");
});
2020-10-20 19:45:26 +00:00
this.socket.addEventListener("close", () => {
2020-10-20 19:29:41 +00:00
console.log("WebSocket closed, retrying connection in 1s...");
setTimeout(this._open, 1000);
});
2020-10-20 19:45:26 +00:00
this.socket.addEventListener("error", () => {
2020-10-20 19:29:41 +00:00
console.log("WebSocket errored, retrying connection in 1s...");
setTimeout(this._open, 1000);
});
}
/**
* Exchange WebRTC session description with server.
2020-10-21 20:10:39 +00:00
* @param {SessionDescription} localDescription WebRTC local SDP
* @param {string} stream Name of the stream
* @param {string} quality Requested quality
2020-10-20 19:29:41 +00:00
*/
2020-10-21 20:10:39 +00:00
sendDescription(localDescription, stream, quality) {
2020-10-20 19:29:41 +00:00
if (this.socket.readyState !== 1) {
console.log("WebSocket not ready to send data");
return;
}
2020-10-21 20:10:39 +00:00
this.socket.send(JSON.stringify({
"webRtcSdp": localDescription,
"stream": stream,
"quality": quality
}));
}
/**
* Set callback function on new session description.
* @param {Function} callback Function called when data is received
*/
onDescription(callback) {
2020-10-20 19:29:41 +00:00
this.socket.addEventListener("message", (event) => {
2020-10-21 20:10:39 +00:00
// FIXME: json to session description
2020-10-20 19:29:41 +00:00
console.log("Message from server ", event.data);
2020-10-21 20:10:39 +00:00
callback(event.data);
2020-10-20 19:29:41 +00:00
});
}
}