muti-client.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { io } from "socket.io-client";
  2. const URL = process.env.URL || "http://127.0.0.1:3000";
  3. const MAX_CLIENTS = 10000;
  4. const POLLING_PERCENTAGE = 0.05;
  5. const CLIENT_CREATION_INTERVAL_IN_MS = 10;
  6. const EMIT_INTERVAL_IN_MS = 1000;
  7. let clientCount = 0;
  8. let lastReport = new Date().getTime();
  9. let packetsSinceLastReport = 0;
  10. const createClient = () => {
  11. // for demonstration purposes, some clients stay stuck in HTTP long-polling
  12. const transports = Math.random() < POLLING_PERCENTAGE ? ["websocket"] : ["websocket", "websocket"];
  13. const socket = io(URL, {
  14. path: "/test",
  15. transports,
  16. });
  17. setInterval(() => {
  18. socket.emit("client to server event");
  19. }, EMIT_INTERVAL_IN_MS);
  20. socket.on("server to client event", () => {
  21. packetsSinceLastReport++;
  22. });
  23. socket.on("disconnect", (reason) => {
  24. console.log(`disconnect due to ${reason}`);
  25. });
  26. if (++clientCount < MAX_CLIENTS) {
  27. setTimeout(createClient, CLIENT_CREATION_INTERVAL_IN_MS);
  28. }
  29. };
  30. createClient();
  31. const printReport = () => {
  32. const now = new Date().getTime();
  33. const durationSinceLastReport = (now - lastReport) / 1000;
  34. const packetsPerSeconds = (packetsSinceLastReport / durationSinceLastReport).toFixed(2);
  35. console.log(`client count: ${clientCount} ; average packets received per second: ${packetsPerSeconds}`);
  36. packetsSinceLastReport = 0;
  37. lastReport = now;
  38. };
  39. setInterval(printReport, 5000);