WebSocket API ใน JavaScript เปิดใช้งานการสื่อสารสองทิศทาง (bidirectional) ระหว่างเว็บแอปกับเซิร์ฟเวอร์แบบ real-time
เมธอดหลัก
// สร้างการเชื่อมต่อใหม่ socket = new WebSocket(url [, protocols]); // ส่งข้อมูล socket.send(data); // ปิดการเชื่อมต่อ socket.close([code] [, reason]); // ดึง URL ที่ใช้เชื่อมต่อ socket.url;
เหตุการณ์ (Events)
onopen- เชื่อมต่อสำเร็จonmessage- ได้รับข้อมูลonerror- เกิดข้อผิดพลาดonclose- ปิดการเชื่อมต่อ
ตัวอย่างการใช้งานพื้นฐาน
const socket = new WebSocket('wss://example.com/socket');
socket.onopen = () => {
console.log('Connected');
socket.send(JSON.stringify({ type: 'hello' }));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
};
socket.onerror = (error) => console.error('WebSocket error:', error);
socket.onclose = () => console.log('Disconnected');
WebSocket ใช้ protocol ws:// หรือ wss:// (secure) เหมาะสำหรับ chat, real-time notifications, collaborative editing, gaming, financial tickers