ft_transcendence/frontend/static/js/api/matchmaking.js
2023-12-26 01:03:09 +01:00

58 lines
939 B
JavaScript

import { Client } from "./client.js";
class MatchMaking
{
/**
* @param {Client} client
*/
constructor(client)
{
/**
* @type {Client}
*/
this.client = client
this.searching = false;
}
async start(receive_func, disconnect_func, mode)
{
if (!await this.client.isAuthentificate())
return null;
let url = `
${window.location.protocol == 'https' ? 'wss' : 'ws'}
://${window.location.host}
/ws/matchmaking/
${mode}
`;
this._socket = new WebSocket(url);
this.searching = true;
this.receive_func = receive_func;
this.disconnect_func = disconnect_func;
this._socket.onmessage = function (event) {
const data = JSON.parse(event.data);
receive_func(data);
};
this._socket.onclose = this.onclose.bind(this);
}
onclose(event)
{
this.stop();
this.disconnect_func(event);
}
async stop()
{
this.searching = false;
this._socket.close()
}
}
export {MatchMaking}