This commit is contained in:
syuilo 2017-05-11 05:08:12 +09:00
parent 3d794980b0
commit c3cef31974
1 changed files with 25 additions and 0 deletions

View File

@ -1,7 +1,12 @@
'use strict';
const ReconnectingWebSocket = require('reconnecting-websocket'); const ReconnectingWebSocket = require('reconnecting-websocket');
import * as riot from 'riot'; import * as riot from 'riot';
import CONFIG from './config'; import CONFIG from './config';
/**
* Home stream connection
*/
class Connection { class Connection {
constructor(me) { constructor(me) {
// BIND ----------------------------------- // BIND -----------------------------------
@ -27,6 +32,10 @@ class Connection {
this.on('i_updated', me.update); this.on('i_updated', me.update);
} }
/**
* Callback of when open connection
* @private
*/
onOpen() { onOpen() {
this.state = 'connected'; this.state = 'connected';
this.trigger('_connected_'); this.trigger('_connected_');
@ -39,11 +48,19 @@ class Connection {
}); });
} }
/**
* Callback of when close connection
* @private
*/
onClose() { onClose() {
this.state = 'reconnecting'; this.state = 'reconnecting';
this.trigger('_closed_'); this.trigger('_closed_');
} }
/**
* Callback of when received a message from connection
* @private
*/
onMessage(message) { onMessage(message) {
try { try {
const msg = JSON.parse(message.data); const msg = JSON.parse(message.data);
@ -53,6 +70,10 @@ class Connection {
} }
} }
/**
* Send a message to connection
* @public
*/
send(message) { send(message) {
// まだ接続が確立されていなかったらバッファリングして次に接続した時に送信する // まだ接続が確立されていなかったらバッファリングして次に接続した時に送信する
if (this.state != 'connected') { if (this.state != 'connected') {
@ -63,6 +84,10 @@ class Connection {
this.socket.send(JSON.stringify(message)); this.socket.send(JSON.stringify(message));
} }
/**
* Close this connection
* @public
*/
close() { close() {
this.socket.removeEventListener('open', this.onOpen); this.socket.removeEventListener('open', this.onOpen);
this.socket.removeEventListener('message', this.onMessage); this.socket.removeEventListener('message', this.onMessage);