v10対応

This commit is contained in:
syuilo 2018-10-11 03:00:54 +09:00
parent b281deb530
commit e81f9a75dc
No known key found for this signature in database
GPG key ID: BDC4C49D06AB9D69
3 changed files with 185 additions and 111 deletions

View file

@ -73,11 +73,11 @@ class Session {
private onMessage = async (msg: any) => { private onMessage = async (msg: any) => {
switch (msg.type) { switch (msg.type) {
case '_init_': this.onInit(msg); break; case '_init_': this.onInit(msg.body); break;
case 'updateForm': this.onUpdateForn(msg); break; case 'updateForm': this.onUpdateForn(msg.body); break;
case 'started': this.onStarted(msg); break; case 'started': this.onStarted(msg.body); break;
case 'ended': this.onEnded(msg); break; case 'ended': this.onEnded(msg.body); break;
case 'set': this.onSet(msg); break; case 'set': this.onSet(msg.body); break;
} }
} }
@ -92,14 +92,14 @@ class Session {
* *
*/ */
private onUpdateForn = (msg: any) => { private onUpdateForn = (msg: any) => {
this.form.find(i => i.id == msg.body.id).value = msg.body.value; this.form.find(i => i.id == msg.id).value = msg.value;
} }
/** /**
* *
*/ */
private onStarted = (msg: any) => { private onStarted = (msg: any) => {
this.game = msg.body; this.game = msg;
// TLに投稿する // TLに投稿する
this.postGameStarted().then(note => { this.postGameStarted().then(note => {
@ -215,14 +215,14 @@ class Session {
let text: string; let text: string;
if (msg.body.game.surrendered) { if (msg.game.surrendered) {
if (this.isSettai) { if (this.isSettai) {
text = serifs.reversi.settaiButYouSurrendered(this.userName); text = serifs.reversi.settaiButYouSurrendered(this.userName);
} else { } else {
text = serifs.reversi.youSurrendered(this.userName); text = serifs.reversi.youSurrendered(this.userName);
} }
} else if (msg.body.winnerId) { } else if (msg.winnerId) {
if (msg.body.winnerId == this.account.id) { if (msg.winnerId == this.account.id) {
if (this.isSettai) { if (this.isSettai) {
text = serifs.reversi.iWonButSettai(this.userName); text = serifs.reversi.iWonButSettai(this.userName);
} else { } else {
@ -252,9 +252,9 @@ class Session {
* *
*/ */
private onSet = (msg: any) => { private onSet = (msg: any) => {
this.o.put(msg.body.color, msg.body.pos); this.o.put(msg.color, msg.pos);
if (msg.body.next === this.botColor) { if (msg.next === this.botColor) {
this.think(); this.think();
} }
} }

View file

@ -66,19 +66,13 @@ export default class ReversiModule implements IModule {
} }
private onReversiGameStart = (game: any) => { private onReversiGameStart = (game: any) => {
console.log('enter reversi game room');
// ゲームストリームに接続 // ゲームストリームに接続
const gw = this.ai.connection.connectToChannel('gamesReversiGame', { const gw = this.ai.connection.connectToChannel('gamesReversiGame', {
game: game.id gameId: game.id
}); });
function send(msg) {
try {
gw.send(JSON.stringify(msg));
} catch (e) {
console.error(e);
}
}
// フォーム // フォーム
const form = [{ const form = [{
id: 'publish', id: 'publish',
@ -114,15 +108,16 @@ export default class ReversiModule implements IModule {
// バックエンドプロセスに情報を渡す // バックエンドプロセスに情報を渡す
ai.send({ ai.send({
type: '_init_', type: '_init_',
game, body: {
form, game: game,
form: form,
account: this.ai.account account: this.ai.account
}
}); });
ai.on('message', msg => { ai.on('message', msg => {
if (msg.type == 'put') { if (msg.type == 'put') {
send({ gw.send('set', {
type: 'set',
pos: msg.pos pos: msg.pos
}); });
} else if (msg.type == 'ended') { } else if (msg.type == 'ended') {
@ -133,24 +128,19 @@ export default class ReversiModule implements IModule {
}); });
// ゲームストリームから情報が流れてきたらそのままバックエンドプロセスに伝える // ゲームストリームから情報が流れてきたらそのままバックエンドプロセスに伝える
gw.addEventListener('*', message => { gw.addListener('*', message => {
ai.send(message); ai.send(message);
}); });
//#endregion //#endregion
// フォーム初期化 // フォーム初期化
setTimeout(() => { setTimeout(() => {
send({ gw.send('initForm', form);
type: 'initForm',
body: form
});
}, 1000); }, 1000);
// どんな設定内容の対局でも受け入れる // どんな設定内容の対局でも受け入れる
setTimeout(() => { setTimeout(() => {
send({ gw.send('accept', {});
type: 'accept'
});
}, 2000); }, 2000);
} }

View file

@ -10,6 +10,8 @@ import config from './config';
export default class Stream extends EventEmitter { export default class Stream extends EventEmitter {
private stream: any; private stream: any;
private state: string; private state: string;
private buffer: any[];
private sharedConnectionPools: Pool[] = [];
private sharedConnections: SharedConnection[] = []; private sharedConnections: SharedConnection[] = [];
private nonSharedConnections: NonSharedConnection[] = []; private nonSharedConnections: NonSharedConnection[] = [];
@ -17,7 +19,7 @@ export default class Stream extends EventEmitter {
super(); super();
this.state = 'initializing'; this.state = 'initializing';
console.log('initializing stream'); this.buffer = [];
this.stream = new ReconnectingWebsocket(`${config.wsUrl}/streaming?i=${config.i}`, [], { this.stream = new ReconnectingWebsocket(`${config.wsUrl}/streaming?i=${config.i}`, [], {
WebSocket: WebSocket WebSocket: WebSocket
@ -27,26 +29,27 @@ export default class Stream extends EventEmitter {
this.stream.addEventListener('message', this.onMessage); this.stream.addEventListener('message', this.onMessage);
} }
public useSharedConnection = (channel: string): SharedConnection => { @autobind
const existConnection = this.sharedConnections.find(c => c.channel === channel); public useSharedConnection(channel: string): SharedConnection {
let pool = this.sharedConnectionPools.find(p => p.channel === channel);
if (existConnection) { if (pool == null) {
existConnection.use(); pool = new Pool(this, channel);
return existConnection; this.sharedConnectionPools.push(pool);
} else { }
const connection = new SharedConnection(this, channel);
connection.use(); const connection = new SharedConnection(this, channel, pool);
this.sharedConnections.push(connection); this.sharedConnections.push(connection);
return connection; return connection;
} }
}
@autobind @autobind
public removeSharedConnection(connection: SharedConnection) { public removeSharedConnection(connection: SharedConnection) {
this.sharedConnections = this.sharedConnections.filter(c => c.id !== connection.id); this.sharedConnections = this.sharedConnections.filter(c => c !== connection);
} }
public connectToChannel = (channel: string, params?: any): NonSharedConnection => { @autobind
public connectToChannel(channel: string, params?: any): NonSharedConnection {
const connection = new NonSharedConnection(this, channel, params); const connection = new NonSharedConnection(this, channel, params);
this.nonSharedConnections.push(connection); this.nonSharedConnections.push(connection);
return connection; return connection;
@ -54,7 +57,7 @@ export default class Stream extends EventEmitter {
@autobind @autobind
public disconnectToChannel(connection: NonSharedConnection) { public disconnectToChannel(connection: NonSharedConnection) {
this.nonSharedConnections = this.nonSharedConnections.filter(c => c.id !== connection.id); this.nonSharedConnections = this.nonSharedConnections.filter(c => c !== connection);
} }
/** /**
@ -66,12 +69,18 @@ export default class Stream extends EventEmitter {
this.state = 'connected'; this.state = 'connected';
this.emit('_connected_'); this.emit('_connected_');
console.log('stream connected');
// バッファーを処理
const _buffer = [].concat(this.buffer); // Shallow copy
this.buffer = []; // Clear buffer
_buffer.forEach(data => {
this.send(data); // Resend each buffered messages
});
// チャンネル再接続 // チャンネル再接続
if (isReconnect) { if (isReconnect) {
this.sharedConnections.forEach(c => { this.sharedConnectionPools.forEach(p => {
c.connect(); p.connect();
}); });
this.nonSharedConnections.forEach(c => { this.nonSharedConnections.forEach(c => {
c.connect(); c.connect();
@ -86,7 +95,6 @@ export default class Stream extends EventEmitter {
private onClose() { private onClose() {
this.state = 'reconnecting'; this.state = 'reconnecting';
this.emit('_disconnected_'); this.emit('_disconnected_');
console.log('stream disconnected');
} }
/** /**
@ -98,9 +106,19 @@ export default class Stream extends EventEmitter {
if (type == 'channel') { if (type == 'channel') {
const id = body.id; const id = body.id;
const connection = this.sharedConnections.find(c => c.id === id) || this.nonSharedConnections.find(c => c.id === id);
connection.emit(body.type, body.body); let connections: Connection[];
connection.emit('*', { type, body });
connections = this.sharedConnections.filter(c => c.id === id);
if (connections.length === 0) {
connections = [this.nonSharedConnections.find(c => c.id === id)];
}
connections.filter(c => c != null).forEach(c => {
c.emit(body.type, body.body);
c.emit('*', { type: body.type, body: body.body });
});
} else { } else {
this.emit(type, body); this.emit(type, body);
this.emit('*', { type, body }); this.emit('*', { type, body });
@ -117,6 +135,12 @@ export default class Stream extends EventEmitter {
body: payload body: payload
}; };
// まだ接続が確立されていなかったらバッファリングして次に接続した時に送信する
if (this.state != 'connected') {
this.buffer.push(data);
return;
}
this.stream.send(JSON.stringify(data)); this.stream.send(JSON.stringify(data));
} }
@ -130,19 +154,131 @@ export default class Stream extends EventEmitter {
} }
} }
abstract class Connection extends EventEmitter { class Pool {
public channel: string; public channel: string;
public id: string; public id: string;
protected params: any;
protected stream: Stream; protected stream: Stream;
private users = 0;
private disposeTimerId: any;
private isConnected = false;
constructor(stream: Stream, channel: string, params?: any) { constructor(stream: Stream, channel: string) {
this.channel = channel;
this.stream = stream;
this.id = Math.random().toString();
}
@autobind
public inc() {
if (this.users === 0 && !this.isConnected) {
this.connect();
}
this.users++;
// タイマー解除
if (this.disposeTimerId) {
clearTimeout(this.disposeTimerId);
this.disposeTimerId = null;
}
}
@autobind
public dec() {
this.users--;
// そのコネクションの利用者が誰もいなくなったら
if (this.users === 0) {
// また直ぐに再利用される可能性があるので、一定時間待ち、
// 新たな利用者が現れなければコネクションを切断する
this.disposeTimerId = setTimeout(() => {
this.disconnect();
}, 3000);
}
}
@autobind
public connect() {
this.isConnected = true;
this.stream.send('connect', {
channel: this.channel,
id: this.id
});
}
@autobind
private disconnect() {
this.isConnected = false;
this.disposeTimerId = null;
this.stream.send('disconnect', { id: this.id });
}
}
abstract class Connection extends EventEmitter {
public channel: string;
protected stream: Stream;
public abstract id: string;
constructor(stream: Stream, channel: string) {
super(); super();
this.stream = stream; this.stream = stream;
this.channel = channel; this.channel = channel;
}
@autobind
public send(id: string, typeOrPayload, payload?) {
const type = payload === undefined ? typeOrPayload.type : typeOrPayload;
const body = payload === undefined ? typeOrPayload.body : payload;
this.stream.send('ch', {
id: id,
type: type,
body: body
});
}
public abstract dispose(): void;
}
class SharedConnection extends Connection {
private pool: Pool;
public get id(): string {
return this.pool.id;
}
constructor(stream: Stream, channel: string, pool: Pool) {
super(stream, channel);
this.pool = pool;
this.pool.inc();
}
@autobind
public send(typeOrPayload, payload?) {
super.send(this.pool.id, typeOrPayload, payload);
}
@autobind
public dispose() {
this.pool.dec();
this.removeAllListeners();
this.stream.removeSharedConnection(this);
}
}
class NonSharedConnection extends Connection {
public id: string;
protected params: any;
constructor(stream: Stream, channel: string, params?: any) {
super(stream, channel);
this.params = params; this.params = params;
this.id = Math.random().toString(); this.id = Math.random().toString();
this.connect(); this.connect();
} }
@ -157,59 +293,7 @@ abstract class Connection extends EventEmitter {
@autobind @autobind
public send(typeOrPayload, payload?) { public send(typeOrPayload, payload?) {
const type = payload === undefined ? typeOrPayload.type : typeOrPayload; super.send(this.id, typeOrPayload, payload);
const body = payload === undefined ? typeOrPayload.body : payload;
this.stream.send('channel', {
id: this.id,
type: type,
body: body
});
}
public abstract dispose(): void;
}
export class SharedConnection extends Connection {
private users = 0;
private disposeTimerId: any;
constructor(stream: Stream, channel: string) {
super(stream, channel);
}
@autobind
public use() {
this.users++;
// タイマー解除
if (this.disposeTimerId) {
clearTimeout(this.disposeTimerId);
this.disposeTimerId = null;
}
}
@autobind
public dispose() {
this.users--;
// そのコネクションの利用者が誰もいなくなったら
if (this.users === 0) {
// また直ぐに再利用される可能性があるので、一定時間待ち、
// 新たな利用者が現れなければコネクションを切断する
this.disposeTimerId = setTimeout(() => {
this.disposeTimerId = null;
this.removeAllListeners();
this.stream.send('disconnect', { id: this.id });
this.stream.removeSharedConnection(this);
}, 3000);
}
}
}
export class NonSharedConnection extends Connection {
constructor(stream: Stream, channel: string, params?: any) {
super(stream, channel, params);
} }
@autobind @autobind