最近遊んでいるAngular2でnode.js側にパラメータを投げてonやemitする値を動的に変えてconnectするものを作ってみようと思って遊んでみたのでメモ
(component単位でconnectするとかあるかのかなぁと妄想して)
node.js側
$ mkdir web-socket
$ cd web-socket
$ npm init
$ npm install socket.io --save
$ npm install express --save
$ touch web-socket.js
web-socket.js
let app = require( 'express' )();
let http = require( 'http' ).Server( app );
let socket_io = require( 'socket.io' )( http );
socket_io.on( 'connection', ( socket ) => {
let query = socket.handshake.query;
let hoge = query.hoge;
socket.on( 'disconnect', function(){} );
socket.on( 'on_name', ( data ) => {
socket_io.emit( 'emit_name', { data: data } );
} );
} );
http.listen( 5000, () => { } );
Angular側
$ npm install socket.io-client --save
$ npm install @types/socket.io-client --save-dev
Service
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class WebSocketService {
constructor(){}
private url = 'http://localhost:5000';
private socket;
connect( queryString: string ){
this.socket = io( this.url, { query: queryString } );
}
emit( emitName: string, data? ){
this.socket.emit( emitName, data );
}
on( onName: string ){
let observable = new Observable( observer => {
this.socket.on( onName, ( data ) => {
observer.next( data );
});
return () => { this.socket.disconnect(); };
} );
return observable;
}
}
Component
import { Component, OnInit, OnDestroy } from '@angular/core';
import { WebSocketService } from './web-socket.service';
@Component({
providers: [WebSocketService],
selector: 'app-web-socket',
templateUrl: './web-socket.component.html',
styleUrls: ['./web-socket.component.scss'],
})
export class WebSocketComponent implements OnInit, OnDestroy {
connection;
data;
constructor( private webSocketService: WebSocketService ){}
onClick(){
this.webSocketService.emit( 'on_name', this.data );
this.data = '';
}
ngOnInit() {
this.webSocketService.connect( 'hoge=hoge' )
this.connection = this.webSocketService.on( 'emit_name' ).subscribe( data => {
this.data = data;
} )
}
ngOnDestroy() {
this.connection.unsubscribe();
}
}
あとは
web-socket.component.htmlに onClick
のボタンを置いて ng serve
と node web-socket.js
をして別々に起動
補足
下記の部分でクエリを受け取っているので、ここで条件分岐等でonやemitの値を動的にセットしてあげれば目的達成
let query = socket.handshake.query;
let hoge = query.hoge;