안녕하세요. IT김군입니다.


Socket.io로 Client에서 통신하는 방법에 대해 적어보도록 하겠습니다.


우선 터미널에서 프로젝트에 패키지를 설치합니다.

$ npm install typings --global
$ typings install dt~socket.io-client --global --save
$ npm install socket.io-client --save



그 다음 Socket.io를 사용하실 페이지에 import 및 생성자에 선언해줍니다.

import { NgZone } from '@angular/core';
import * as io from 'socket.io-client';

export class HomePage{
    constructor(private zone : NgZone){}
}



아래는 socket.io를 연결하는 부분입니다.


socket.io를 연결할 URL에는 http 혹은 https를 무조건 붙여주도록 합니다. (붙이지 않으면 Android에서 인식하지 못합니다.)


아래 console.log 부분의 "this._any_socket.id"는 socket.io가 연결되지 않을 시 undefined로 값이 나오며, socket.io가 연결되었다면 그 id값이 나오게 됩니다.

private _str_socketURL : string = "http://www.yourURL.co.kr:0000";
private _any_socket : any;
private _strarr_chats : string[];

socketConnect(){
   this._any_socket = io(this._str_socketURL);
   this._strarr_chats = [];
   this._any_socket.on('connect', () => {
      console.log("@@ Socket Connect Check : "+this._any_socket.id);
   });
}




이제 socket.io로 연결을 했으니 서버로 정보를 송신해보겠습니다.


아래와 같이 정보를 보내며 'sendEvent'는 서버측과 정해놓은 이벤트 명입니다.


SendValue는 서버측으로 송신할 정보입니다.


이벤트의 경우 서버측과 협의하여야 하며, 이벤트 명을 맞추어 그에 따른 동작에 대해 작업하여야 합니다.

socketSendMsg(){
   this._any_socket.emit('sendEvent', SendValue);
}




이제 보냈으니 받는 부분도 해봐야겠죠?


받는 부분도 보내는 부분과 비슷한 점은 서버측과 협의된 이벤트가 있어야한다는 점입니다. (receiveEvent로 기재했습니다.)


그리고 아래 나온 _strarr_chats는 아까 connect 부분에서 초기화시켜준 변수입니다.

socketReceiveMsg(){
   this._any_socket.on('receiveEvent', (receiveMsg) => {
      this.zone.run(() => {
         this._strarr_chats.push(receiveMsg);
         console.log(receiveMsg);
      })
   });
}




마지막으로 socket.io 연결을 끊는 동작입니다.

socketDisconnect(){
   this._any_socket.disconnect();
}


Socket.io로 서버와 통신하는 기본적인 부분만 기재해보았습니다.


진짜 기본적인 기능만 기재하였고 추가적인 기능은 API를 참조하시면 될 것 같습니다.


Socket.io API  <---- Client API 링크 남깁니다.


감사합니다.


WRITTEN BY
IT김군
S/W 개발자 김군의 메모장

,