Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class SocketManager
- {
- constructor()
- {
- this.socket = null;
- this.didOpen = false;
- }
- connect(url)
- {
- if(this.socket) this.socket.close();
- this.didOpen = false;
- return new Promise((resolve, reject) =>
- {
- this.socket = new WebSocket(url);
- this.socket.onopen = event =>
- {
- this.didOpen = true;
- resolve();
- }
- this.socket.onerror = event =>
- {
- if(!this.didOpen)
- {
- reject();
- }
- else
- {
- this.onError(event);
- }
- }
- this.socket.onmessage = this.onMessage.bind(this);
- this.socket.onclose = this.onClose.bind(this);
- });
- }
- sendMessage(message)
- {
- this.socket.send(message);
- }
- onMessage(event)
- {
- // we received a message
- console.log(event);
- }
- onClose(event)
- {
- // the socket server closed
- console.log(event);
- }
- onError(event)
- {
- // we received some error
- console.log(event);
- }
- get socket()
- {
- return this.socket;
- }
- }
- // use it like this
- const socket = new SocketManager();
- function connect(url)
- {
- socket
- .connect(url)
- .then(() =>
- {
- // the socket was connected, now lets login
- socket.sendMessage('{{ Auth::user()->auth_ticket }}');
- // now we can start doing things
- })
- .catch(error =>
- {
- // the socket didnt connect, check the error
- console.log(error);
- });
- }
- connect('ws://');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement