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

53 lines
1.6 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.
*
* @param {string} data JSON formated data
* @param {Function} receiveCallback Function called when data is received
*/
exchangeDescription(data, receiveCallback) {
if (this.socket.readyState !== 1) {
console.log("WebSocket not ready to send data");
return;
}
this.socket.send(data);
this.socket.addEventListener("message", (event) => {
console.log("Message from server ", event.data);
receiveCallback(event);
});
}
}