longpoll.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const http = require("http");
  2. const fs = require("fs");
  3. const path = require("path");
  4. // Store clients waiting for a message
  5. let clients = [];
  6. function sendToWebConsoleClient(client, message) {
  7. return new Promise((resolve, reject) => {
  8. client.writeHead(200, { "Content-Type": "application/json" });
  9. client.end(JSON.stringify({ message }), (err) => {
  10. if (err) {
  11. reject(err);
  12. } else {
  13. resolve();
  14. }
  15. });
  16. });
  17. }
  18. const messages = [];
  19. // Function to send a message to a specific client
  20. function sendToWebConsole(message) {
  21. messages.push(message);
  22. // Promise.all(clients.map((client) => sendToWebConsoleClient(client, message)));
  23. // clients = [];
  24. }
  25. exports.sendToWebConsole = sendToWebConsole;
  26. // Function to end the connection
  27. function endConnection(client, cb) {
  28. client.writeHead(200, { "Content-Type": "text/plain" });
  29. client.end("Connection ended", cb);
  30. // clients = clients.filter((c) => c !== client);
  31. }
  32. exports.endConnection = endConnection;
  33. http
  34. .createServer(function (req, res) {
  35. if (req.url === "/poll") {
  36. // Add client to the list
  37. // clients.push(res);
  38. res.writeHead(200, { "Content-Type": "text/json" });
  39. res.end(JSON.stringify({ messages }));
  40. // Set a timeout to end the connection if no message is received within a certain time
  41. // setTimeout(() => {
  42. // endConnection(res);
  43. // }, 30000); // 30 seconds timeout
  44. } else if (req.url === "/" || req.url === "/index.html") {
  45. // Serve the HTML page
  46. const filePath = path.join(__dirname, "index.html");
  47. fs.readFile(filePath, (err, data) => {
  48. if (err) {
  49. res.writeHead(500, { "Content-Type": "text/plain" });
  50. res.end("Server Error");
  51. } else {
  52. res.writeHead(200, { "Content-Type": "text/html" });
  53. res.end(data);
  54. }
  55. });
  56. } else {
  57. res.writeHead(404, { "Content-Type": "text/plain" });
  58. res.end("Not Found");
  59. }
  60. })
  61. .listen(8081);