web socket

박경준·2023년 6월 26일
2

핀랩 어드민

목록 보기
1/1

SPA 사이트는 특성상 배포를 할때마다 새로고침을 해야만 유저가 새 리소스를 다운받아 배포된 코드를 접할 수 있다. 그런데 새로고침을 해달라고 그때마다 말하는게 귀찮아서 web socket을 이용해 실시간으로 알림을 보내보자!

  • web socket을 처음부터 만드는건 힘드니 pusher라는 서비스를 이용하자.
  • 내 사이트는 csr이므로 별도의 서버 프로젝트를 만들자.
  • express로 post 메소드를 연결하고 그 안에 trigger를 만든다.
  • cors는 모두 열어둠
  • cloudtype에 배포
// ./server.js
/*
 * Initialise Express
 */
const express = require('express');
var cors = require('cors');
const path = require('path');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname)));
app.use(cors());

/*
 * Initialise Pusher
 */
const Pusher = require('pusher');
const pusher = new Pusher({
  appId: '',
  key: '',
  secret: '',
  cluster: '',
  useTLS: true,
});

/*
 * Define post route for creating new reviews
 */
app.post('/release-alarm', (req, res) => {
  pusher.trigger('my-channel', 'my-event', req.body);
  res.status(200).send();
});

/*
 * Run app
 */
const port = 3001;
app.listen(port, () => {
  console.log(`App listening on port ${port}!`);
});
  • pusher를 구독하고, 이벤트 bind 하여 콜백을 정의한다.
  • alarm이 true가 되면 모달을 띄워서 강력 새로고침 하도록 유도
// ./App.vue
<script setup>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;

var pusher = new Pusher('', {
  cluster: '',
});

var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function (data) {
  pusherRefresh.value = data.alarm;
});

const clickResetConfirm = () => {
  // 강력 새로고침
  window.location.href = `${window.location.origin}${window.location.pathname}?refresh=` + new Date().getTime();
};
</script>

<template>
  <el-dialog
    v-model="pusherRefresh"
    title="새로고침 하기"
    width="30%"
    :before-close="handleClose"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
  >
    <div style="font-size: 16px; padding-bottom: 16px">주요 기능이 배포되어 <b>새로고침</b>이 필요합니다. <b>새로고침 버튼</b>을 눌러주세요.</div>
    <div>
      진행중인 작업이 있으실 경우 닫기 버튼을 누른 후 하던 작업을 마무리 하고, 반드시 <b>'Ctrl + Shift + R'</b>를 눌러 강력 새로고침 해주세요.
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="clickResetConfirm"> 새로고침 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
  • axios post로 socket 구독자들에게 신호를 보냄.
<script setup>
import pureAxios from 'axios';

const clickBtn = async () => {
  await pureAxios.post(
    '/release-alarm',
    { alarm: true },
    { 'Content-Type': 'application/json' },
  );
};
</script>
<template>
  <el-button type="default" size="large" @click="clickBtn">배포 알람</el-button>
</template>
profile
빠굥

0개의 댓글