웹사이트 검색

Vue.js와 Socket.io 통합


Websocket은 클라이언트와 서버 간의 양방향 통신을 가능하게 하는 강력한 방법이며 socket.io는 websocket 및 대체 전송으로 연결 처리를 단순화하는 주요 라이브러리 중 하나입니다. 컴포넌트에서 직접 socket.io를 사용할 수 있도록 Vue와 결합합시다!

설치

먼저 Yarn 또는 NPM을 사용하여 socket.io-clientvue-socket.io를 설치하겠습니다.

# Yarn
$ yarn add socket.io-client vue-socket.io
# NPM
$ npm install socket.io-client vue-socket.io --save

용법

이 가이드의 목적상 로컬에서 socket.io로 실행 중인 서버가 이미 있다고 가정합니다. 예를 들어 포트 4113입니다.

먼저 앱 시작 파일에서 vue-socket.io 플러그인을 활성화합니다.

import Vue from 'vue';
import socketio from 'socket.io';
import VueSocketIO from 'vue-socket.io';

export const SocketInstance = socketio('http://localhost:4113');

Vue.use(VueSocketIO, SocketInstance)

// The usual app stuff goes here.
...

이제 구성 요소에서 직접 소켓 이벤트에 바인딩할 수 있습니다.

<template>
  <div>
    <p v-if="isConnected">We're connected to the server!</p>
    <p>Message from server: "{{socketMessage}}"</p>
    <button @click="pingServer()">Ping Server</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isConnected: false,
      socketMessage: ''
    }
  },

  sockets: {
    connect() {
      // Fired when the socket connects.
      this.isConnected = true;
    },

    disconnect() {
      this.isConnected = false;
    },

    // Fired when the server sends something on the "messageChannel" channel.
    messageChannel(data) {
      this.socketMessage = data
    }
  },

  methods: {
    pingServer() {
      // Send the "pingServer" event to the server.
      this.$socket.emit('pingServer', 'PING!')
    }
  }
}
</script>

Vuex 통합

Vuex를 사용하는 경우 main.js의 플러그인 초기화에 Vuex 스토어를 추가하기만 하면 소켓 채널이 메시지를 수신할 때 스토어 변형이 실행되도록 할 수 있습니다.

...
import { MyVuexStore } from './my-vuex-store.js'

Vue.use(VueSocketIO, SocketInstance, MyVuexStore)
...

소켓에 의해 트리거되는 모든 변형에는 SOCKET_ 접두사가 붙습니다.

예를 들어 채널 이름이 messageChannel인 경우 해당 Vuex 변형은 SOCKET_MESSAGECHANNEL입니다. 상점 구성에서 다음과 같이 표시됩니다.


import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    isConnected: false,
    socketMessage: ''
  },

  mutations:{
    SOCKET_CONNECT(state) {
      state.isConnected = true;
    },

    SOCKET_DISCONNECT(state) {
      state.isConnected = false;
    },

    SOCKET_MESSAGECHANNEL(state, message) {
      state.socketMessage = message
    }
  }
})

나쁘지 않죠?

자세한 내용은 socket.io 설명서를 참조하십시오.