This commit is contained in:
AdisakKanthawilang 2025-03-07 16:29:28 +07:00
parent e976e51860
commit 1ea3392a8f
3 changed files with 55 additions and 56 deletions

View file

@ -1,16 +1,43 @@
import { WebSocket } from "ws";
import { wss } from "../app";
import { WebSocketServer } from "ws";
export async function sendWebSocket(data:any){
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);
}
});
}
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);
});
});
}
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);
}
});
}
});
}