2020-04-11 11:30:15 -04:00
|
|
|
/*
|
|
|
|
* Copyright © 2020 Luciano Iam <lucianito@gmail.com>
|
|
|
|
*
|
|
|
|
* This program is free software; you can redistribute it and/or modify
|
|
|
|
* it under the terms of the GNU General Public License as published by
|
|
|
|
* the Free Software Foundation; either version 2 of the License, or
|
|
|
|
* (at your option) any later version.
|
|
|
|
*
|
|
|
|
* This program is distributed in the hope that it will be useful,
|
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
* GNU General Public License for more details.
|
|
|
|
*
|
|
|
|
* You should have received a copy of the GNU General Public License along
|
|
|
|
* with this program; if not, write to the Free Software Foundation, Inc.,
|
|
|
|
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
|
|
*/
|
|
|
|
|
2020-04-12 09:49:54 -04:00
|
|
|
import { ANode, Message } from './message.js';
|
2020-04-12 06:38:49 -04:00
|
|
|
|
2020-04-12 05:29:01 -04:00
|
|
|
export class MessageChannel {
|
2020-04-11 11:30:15 -04:00
|
|
|
|
2020-04-12 06:19:11 -04:00
|
|
|
constructor (host) {
|
|
|
|
// https://developer.mozilla.org/en-US/docs/Web/API/URL/host
|
2020-04-12 09:36:51 -04:00
|
|
|
this._host = host;
|
2020-04-12 06:19:11 -04:00
|
|
|
}
|
2020-04-11 11:30:15 -04:00
|
|
|
|
2020-04-12 08:37:44 -04:00
|
|
|
async open () {
|
2020-04-12 06:19:11 -04:00
|
|
|
return new Promise((resolve, reject) => {
|
2020-04-12 09:36:51 -04:00
|
|
|
this._socket = new WebSocket(`ws://${this._host}`);
|
2020-04-12 06:01:41 -04:00
|
|
|
|
2020-04-13 03:05:30 -04:00
|
|
|
this._socket.onclose = () => this.onClose();
|
2020-04-12 06:01:41 -04:00
|
|
|
|
2020-04-13 03:05:30 -04:00
|
|
|
this._socket.onerror = (error) => this.onError(error);
|
2020-04-12 06:01:41 -04:00
|
|
|
|
2020-04-12 09:36:51 -04:00
|
|
|
this._socket.onmessage = (event) => {
|
2020-04-13 03:05:30 -04:00
|
|
|
this.onMessage (Message.fromJsonText(event.data));
|
2020-04-12 06:19:11 -04:00
|
|
|
};
|
2020-04-12 06:01:41 -04:00
|
|
|
|
2020-04-12 09:36:51 -04:00
|
|
|
this._socket.onopen = resolve;
|
2020-04-12 06:19:11 -04:00
|
|
|
});
|
|
|
|
}
|
2020-04-11 11:45:52 -04:00
|
|
|
|
2020-04-13 03:05:30 -04:00
|
|
|
close () {
|
2020-04-12 09:36:51 -04:00
|
|
|
this._socket.close();
|
|
|
|
}
|
|
|
|
|
2020-04-12 06:19:11 -04:00
|
|
|
send (msg) {
|
2020-04-12 09:36:51 -04:00
|
|
|
if (this._socket) {
|
|
|
|
this._socket.send(msg.toJsonText());
|
2020-04-12 08:51:54 -04:00
|
|
|
} else {
|
|
|
|
throw Error('MessageChannel: cannot call send() before open()');
|
|
|
|
}
|
2020-04-12 06:19:11 -04:00
|
|
|
}
|
2020-04-12 06:01:41 -04:00
|
|
|
|
2020-04-13 03:05:30 -04:00
|
|
|
onClose () {}
|
|
|
|
onError (error) {}
|
|
|
|
onMessage (msg) {}
|
2020-04-11 11:30:15 -04:00
|
|
|
|
2020-04-12 06:01:41 -04:00
|
|
|
}
|