ft_transcendence/frontend/static/js/api/matchmaking.js

52 lines
871 B
JavaScript
Raw Normal View History

2023-12-16 12:00:38 -05:00
import { Client } from "./client.js";
2023-12-12 06:06:13 -05:00
class MatchMaking
{
/**
2023-12-16 12:00:38 -05:00
* @param {Client} client
2023-12-12 06:06:13 -05:00
*/
constructor(client)
{
/**
2023-12-20 13:10:26 -05:00
* @type {Client}
2023-12-12 06:06:13 -05:00
*/
this.client = client
this.searching = false;
2023-12-12 06:06:13 -05:00
}
async start(receive_func, disconnect_func, mode)
2023-12-12 06:06:13 -05:00
{
if (!await this.client.isAuthentificate())
return null;
let url = `wss://${window.location.host}/ws/matchmaking/${mode}`;
2023-12-12 06:06:13 -05:00
this._socket = new WebSocket(url);
2023-12-12 06:06:13 -05:00
this.searching = true;
this.receive_func = receive_func;
this.disconnect_func = disconnect_func;
this._socket.onmessage = function (event) {
2023-12-12 06:06:13 -05:00
const data = JSON.parse(event.data);
receive_func(data);
2023-12-12 06:06:13 -05:00
};
this._socket.onclose = this.onclose.bind(this);
}
onclose(event)
{
this.stop();
this.disconnect_func(event);
2023-12-12 06:06:13 -05:00
}
async stop()
{
this.searching = false;
this._socket.close()
2023-12-12 06:06:13 -05:00
}
}
export {MatchMaking}