2025-03-07 16:29:28 +07:00
|
|
|
import { WebSocketServer } from "ws";
|
2025-03-06 18:25:27 +07:00
|
|
|
|
2025-03-07 16:29:28 +07:00
|
|
|
let wss: WebSocketServer;
|
|
|
|
|
|
|
|
|
|
export function initWebSocket() {
|
|
|
|
|
wss = new WebSocketServer({ port: 13002, path: "/api/v1/org-socket" });
|
|
|
|
|
|
|
|
|
|
// การจัดการคำขออัปเกรดจาก HTTP เป็น WebSocket
|
|
|
|
|
wss.on("upgrade", (request: any, socket: any, head: any) => {
|
|
|
|
|
console.log("🔹 Handling upgrade request...");
|
|
|
|
|
wss.handleUpgrade(request, socket, head, (ws: any) => {
|
|
|
|
|
console.log("🔹 WebSocket connection established");
|
|
|
|
|
wss.emit("connection", ws, request);
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
wss.on("connection", (ws: any) => {
|
|
|
|
|
console.log("✅ Client connected to WebSocket");
|
|
|
|
|
|
|
|
|
|
ws.on("close", () => {
|
|
|
|
|
console.log("❌ Client disconnected");
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
ws.on("error", (error: any) => {
|
|
|
|
|
console.error("WebSocket error:", error);
|
2025-03-07 12:36:03 +07:00
|
|
|
});
|
2025-03-07 16:29:28 +07:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function sendWebSocket(data: any) {
|
|
|
|
|
if (!wss) initWebSocket();
|
|
|
|
|
wss.clients.forEach((client: any) => {
|
|
|
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
|
|
|
const message = JSON.stringify(data);
|
|
|
|
|
console.log("📤 Sending data to client:", message);
|
|
|
|
|
client.send(message, (err: any) => {
|
|
|
|
|
if (err) {
|
|
|
|
|
console.error("❌ Error sending message:", err);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|