5
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Angular2 + Socket.ioで遊んでみる

Last updated at Posted at 2017-02-18

最近遊んでいる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 servenode web-socket.jsをして別々に起動

補足

下記の部分でクエリを受け取っているので、ここで条件分岐等でonやemitの値を動的にセットしてあげれば目的達成

  let query       = socket.handshake.query;
  let hoge        = query.hoge;
5
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?