[javascript] 앵귤러와 실시간 통신(Socket.IO) 개발

이번 포스트에서는 앵귤러(Angular)와 실시간 통신을 위한 Socket.IO 라이브러리를 사용해서 개발하는 방법에 대해 알아보겠습니다.

Socket.IO란?

Socket.IO는 웹 소켓(WebSocket)을 기반으로 실시간 양방향 통신을 구현할 수 있는 JavaScript 라이브러리입니다. 이를 통해 서버와 클라이언트 간에 실시간으로 데이터를 주고받을 수 있습니다.

앵귤러에서 Socket.IO 사용하기

  1. 앵귤러 프로젝트 생성하기

먼저 앵귤러 프로젝트를 생성합니다. 다음 명령을 터미널에 입력하여 앵귤러 프로젝트를 생성합니다.

ng new my-app
  1. Socket.IO 패키지 설치하기

Socket.IO를 사용하기 위해 npm 패키지를 설치합니다. 다음 명령을 터미널에 입력합니다.

npm install socket.io-client --save
  1. Socket.IO 서버와 연결하기

앵귤러에서 Socket.IO를 사용하기 위해 socket.io-client 모듈을 임포트합니다. 다음과 같이 app.component.ts 파일에 추가합니다.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  socket: any;

  constructor() {
    this.socket = io('http://localhost:3000');
  }
}

위 코드에서 iosocket.io-client 모듈을 임포트한 것이며, this.socket = io('http://localhost:3000'); 부분에서 Socket.IO 서버에 연결합니다. 서버 주소는 각자의 환경에 맞게 변경해주어야 합니다.

  1. 이벤트 핸들링하기

Socket.IO를 사용하면 서버와 클라이언트 간에 이벤트를 주고받을 수 있습니다. 다음과 같이 app.component.ts 파일에 이벤트 핸들러를 추가합니다.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  socket: any;

  constructor() {
    this.socket = io('http://localhost:3000');
    this.socket.on('message', (data: any) => {
      console.log(data);
    });
  }
}

위 코드에서 this.socket.on('message', ...) 부분은 서버로부터 message 이벤트를 수신할 때 실행될 함수를 정의한 것입니다. 이 예제에서는 수신된 데이터를 콘솔에 출력하도록 했습니다.

  1. 데이터 전송하기

앵귤러에서 Socket.IO를 사용하여 서버로 데이터를 전송하는 방법입니다. 다음과 같이 코드를 추가합니다.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  socket: any;
  message: string;

  constructor() {
    this.socket = io('http://localhost:3000');
    this.socket.on('message', (data: any) => {
      console.log(data);
    });
  }

  sendMessage() {
    this.socket.emit('message', this.message);
    this.message = '';
  }
}

위 코드에서 sendMessage() 함수는 클라이언트에서 서버로 메시지를 전송하는 함수입니다. this.socket.emit('message', this.message) 부분에서 message 이벤트와 함께 입력한 메시지를 서버로 보냅니다. 이 예제에서는 전송 후 입력 필드를 비워줍니다.

정리

이제 앵귤러와 Socket.IO를 사용하여 실시간 통신을 구현하는 방법에 대해 알아보았습니다. Socket.IO를 사용하면 웹 애플리케이션에서 실시간으로 데이터를 주고받을 수 있어서 다양한 실시간 애플리케이션 개발에 유용하게 활용할 수 있습니다.

더 자세한 내용은 Socket.IO 공식 문서를 참고하시기 바랍니다.