test websocket

This commit is contained in:
DESKTOP-1R2VSQH\Lenovo ThinkPad E490 2025-03-06 15:59:17 +07:00
parent 43ba731850
commit 9e14183ac7
3 changed files with 2334 additions and 1923 deletions

View file

@ -10,6 +10,14 @@ import { RegisterRoutes } from "./routes";
import logMiddleware from "./middlewares/logs";
import axios from "axios";
import http from "http";
import { WebSocket, WebSocketServer } from "ws"; // ✅ Import WebSocket
// ✅ สร้าง WebSocket Server โดยใช้ HTTP Server เดียวกัน
export const wss = new WebSocketServer({ noServer: true });
async function main() {
await AppDataSource.initialize();
@ -18,7 +26,7 @@ async function main() {
app.use(
cors({
origin: "*",
}),
})
);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
@ -56,7 +64,7 @@ async function main() {
accept: "application/pdf",
},
responseType: "arraybuffer",
},
}
);
console.log("Response:", apiResponse.data);
@ -75,16 +83,49 @@ async function main() {
RegisterRoutes(app);
app.use(error);
app.use(cors());
const APP_HOST = process.env.APP_HOST || "0.0.0.0";
const APP_PORT = +(process.env.APP_PORT || 3000);
app.listen(
// ✅ สร้าง HTTP Server และเชื่อม Express
const server = http.createServer(app);
// ✅ WebSocket Handling
wss.on("connection", (ws) => {
console.log("✅ WebSocket Client Connected");
// clients.add(ws); // เก็บ client ไว้
// ✅ ตั้ง Heartbeat (ping/pong)
ws.on("message", (message) => {
console.log("📩 Received:", message.toString());
ws.send("📡 Server Received: " + message.toString());
});
ws.on("close", () => {
console.log("❌ WebSocket Client Disconnected");
});
});
// ✅ อัปเกรด HTTP เป็น WebSocket
server.on("upgrade", (req, socket, head) => {
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit("connection", ws, req);
});
});
server.listen(
APP_PORT,
APP_HOST,
() => (
console.log(`[APP] Application is running on: http://localhost:${APP_PORT}`),
console.log(`[APP] Swagger on: http://localhost:${APP_PORT}/api-docs`)
),
console.log(
`[APP] Application is running on: http://localhost:${APP_PORT}`
),
console.log(`[APP] Swagger on: http://localhost:${APP_PORT}/api-docs`),
console.log(
`[WS] WebSocket Server is running on ws://localhost:${APP_PORT}`
)
)
);
}

File diff suppressed because it is too large Load diff