monkeeShark/src/web/app/common/scripts/stream.js

60 lines
1.5 KiB
JavaScript
Raw Normal View History

2017-02-18 04:18:59 +00:00
const ReconnectingWebSocket = require('reconnecting-websocket');
2017-03-18 11:05:11 +00:00
import * as riot from 'riot';
import CONFIG from './config';
class Connection {
constructor(me) {
// BIND -----------------------------------
this.onOpen = this.onOpen.bind(this);
this.onClose = this.onClose.bind(this);
this.onMessage = this.onMessage.bind(this);
this.close = this.close.bind(this);
// ----------------------------------------
this.state = 'initializing';
this.stateEv = riot.observable();
this.event = riot.observable();
this.me = me;
const host = CONFIG.apiUrl.replace('http', 'ws');
this.socket = new ReconnectingWebSocket(`${host}?i=${me.token}`);
this.socket.addEventListener('open', this.onOpen);
this.socket.addEventListener('close', this.onClose);
this.socket.addEventListener('message', this.onMessage);
this.event.on('i_updated', me.update);
}
onOpen() {
this.state = 'connected';
this.stateEv.trigger('connected');
}
onClose() {
this.state = 'reconnecting';
this.stateEv.trigger('closed');
}
onMessage(message) {
2017-02-18 04:18:59 +00:00
try {
2017-02-18 23:02:59 +00:00
const msg = JSON.parse(message.data);
2017-03-18 11:05:11 +00:00
if (msg.type) this.event.trigger(msg.type, msg.body);
} catch(e) {
2017-02-18 04:18:59 +00:00
// noop
}
2017-03-18 11:05:11 +00:00
}
2017-02-18 04:18:59 +00:00
2017-03-20 04:54:59 +00:00
send(message) {
2017-03-20 05:35:00 +00:00
// TODO: バッファリングしてつぎ接続した時に送信する
if (this.state != 'connected') return;
2017-03-20 04:54:59 +00:00
this.socket.send(JSON.stringify(message));
}
2017-03-18 11:05:11 +00:00
close() {
this.socket.removeEventListener('open', this.onOpen);
this.socket.removeEventListener('message', this.onMessage);
}
}
2017-02-18 04:18:59 +00:00
2017-03-18 11:05:11 +00:00
export default Connection;