Office.in.th
คู่มือระบบ เนื้อหาผ่านการตรวจสอบแล้ว

การเพิ่มฟีเจอร์แบบ Realtime ในแอปพลิเคชัน Vue.js ด้วย WebSocket

WebSocket เป็นโปรโตคอลสำหรับการสื่อสารแบบสองทาง (bidirectional communication) ที่ช่วยให้การอัปเดตข้อมูลระหว่าง Client และ Server เป็นไปแบบ Realtime เหมาะสำหรับแ...

1. ทำไมต้องใช้ WebSocket?

WebSocket เป็นโปรโตคอลสำหรับการสื่อสารแบบสองทาง (bidirectional communication) ที่ช่วยให้การอัปเดตข้อมูลระหว่าง Client และ Server เป็นไปแบบ Realtime เหมาะสำหรับแอปพลิเคชันที่ต้องการข้อมูลแบบทันที เช่น:

  • ระบบแชท
  • Dashboard Realtime
  • การแจ้งเตือนทันที (Push Notification)

2. วิธีการทำงานของ WebSocket

WebSocket สร้างการเชื่อมต่อที่คงอยู่ระหว่าง Client และ Server โดยทั้งสองฝ่ายสามารถส่งข้อมูลไปมาได้ตลอดเวลา โดยไม่ต้องเปิดการเชื่อมต่อใหม่ในทุกคำขอ


3. การใช้งาน WebSocket ใน Vue.js

3.1 การสร้าง WebSocket Connection

ใช้ JavaScript WebSocket API เพื่อสร้างการเชื่อมต่อ

ตัวอย่าง:

const socket = new WebSocket('ws://localhost:8080');

socket.onopen = () => {
  console.log('WebSocket is connected');
  socket.send('Hello Server!');
};

socket.onmessage = (event) => {
  console.log('Message from server: ', event.data);
};

socket.onclose = () => {
  console.log('WebSocket is closed');
};

socket.onerror = (error) => {
  console.error('WebSocket error: ', error);
};

3.2 การเชื่อม WebSocket กับ Vue Component

ตัวอย่าง:

<template>
  <div>
    <h1>Realtime Messages</h1>
    <ul>
      <li v-for="message in messages" :key="message">{{ message }}</li>
    </ul>
    <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="Type a message" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      socket: null,
      messages: [],
      newMessage: ''
    };
  },
  methods: {
    sendMessage() {
      if (this.newMessage.trim()) {
        this.socket.send(this.newMessage);
        this.newMessage = '';
      }
    }
  },
  mounted() {
    this.socket = new WebSocket('ws://localhost:8080');

    this.socket.onmessage = (event) => {
      this.messages.push(event.data);
    };
  },
  beforeUnmount() {
    this.socket.close();
  }
};
</script>

4. การใช้ไลบรารี Socket.IO

Socket.IO ช่วยเพิ่มความสะดวกในการจัดการ WebSocket และรองรับฟีเจอร์เพิ่มเติม เช่น การ Retry เมื่อการเชื่อมต่อล้มเหลว

การติดตั้ง Socket.IO:

npm install socket.io-client

การใช้งานใน Vue.js:

ตัวอย่าง:

import { io } from 'socket.io-client';

export default {
  data() {
    return {
      socket: null,
      messages: []
    };
  },
  methods: {
    sendMessage(message) {
      this.socket.emit('chat message', message);
    }
  },
  mounted() {
    this.socket = io('http://localhost:3000');

    this.socket.on('chat message', (msg) => {
      this.messages.push(msg);
    });
  },
  beforeUnmount() {
    this.socket.disconnect();
  }
};

5. การตั้งค่า WebSocket Server ด้วย Node.js

การติดตั้ง WebSocket Server:

npm install ws

ตัวอย่างเซิร์ฟเวอร์ WebSocket:

const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (socket) => {
  console.log('Client connected');

  socket.on('message', (message) => {
    console.log('Received: ', message);
    server.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });

  socket.on('close', () => {
    console.log('Client disconnected');
  });
});

6. การปรับปรุงประสิทธิภาพและความปลอดภัยของ WebSocket

6.1 การจัดการ Connection Limit

  • จำกัดจำนวนการเชื่อมต่อพร้อมกันเพื่อป้องกันการใช้งานทรัพยากรเกินขอบเขต

6.2 การตรวจสอบ Token

  • ใช้ JWT (JSON Web Token) เพื่อยืนยันตัวตนของผู้ใช้ก่อนอนุญาตให้เชื่อมต่อ

ตัวอย่าง:

const WebSocket = require('ws');
const jwt = require('jsonwebtoken');

const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (socket, req) => {
  const token = req.headers['sec-websocket-protocol'];
  try {
    const decoded = jwt.verify(token, 'your-secret-key');
    console.log('User authenticated:', decoded);
  } catch (err) {
    console.log('Invalid token');
    socket.close();
  }
});

6.3 การใช้ Load Balancer

  • ใช้ Load Balancer เช่น Nginx เพื่อกระจายการเชื่อมต่อไปยังหลายเซิร์ฟเวอร์

ตัวอย่างการตั้งค่า Nginx:

upstream websocket_servers {
  server 127.0.0.1:8080;
  server 127.0.0.1:8081;
}

server {
  listen 80;

  location / {
    proxy_pass http://websocket_servers;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }
}

7. สรุป

ในบทนี้ คุณได้เรียนรู้วิธีเพิ่มฟีเจอร์แบบ Realtime ในแอปพลิเคชัน Vue.js โดยใช้ WebSocket และ Socket.IO พร้อมทั้งเรียนรู้การตั้งค่า WebSocket Server และการเพิ่มความปลอดภัย เช่น การใช้ JWT และ Load Balancer การเพิ่มฟีเจอร์ Realtime ช่วยให้แอปพลิเคชันตอบสนองต่อผู้ใช้ได้ทันทีและสร้างประสบการณ์ที่ดีขึ้น

ในบทถัดไป เราจะพูดถึงการบูรณาการแอปพลิเคชัน Vue.js กับเทคโนโลยี Serverless!

Office.in.th Custom Service

ต้องการพัฒนาระบบหรือปรับแต่งจากโครงสร้างนี้?

Office.in.th รับพัฒนาและออกแบบ Enterprise Web Application, API Integration และระบบบริหารงานภาครัฐ/เอกชน พร้อมการสนับสนุนระยะยาว

ดูบริการรับพัฒนาซอฟต์แวร์