aboutsummaryrefslogtreecommitdiff
path: root/bench/socketio/client.js
blob: 066a0648300dc50113450bf0783f4a8b19eda6a9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const { io } = require("socket.io-client");
const port = process.env.PORT || 3000;

const URL = `ws://localhost:${port}`;
const MAX_CLIENTS = 250;
const BATCHSIZE = MAX_CLIENTS / 10;
const BATCH_INTERVAL_IN_MS = 1000;
const EMIT_INTERVAL_IN_MS = 50;

let clientCount = 0;
let lastReport = new Date().getTime();
let packetsSinceLastReport = 0;

const clients = [];
const createClient = () => {
  const socket = io(URL);
  clients.push(socket);

  socket.on("server to client event", () => {
    packetsSinceLastReport++;
  });

  socket.on("disconnect", reason => {
    console.log(`disconnect due to ${reason}`);
  });
};

let emitInterval = null;

const createClients = () => {
  for (let i = 0; i < BATCHSIZE; i++) {
    createClient();
    clientCount++;
  }

  if (clientCount < MAX_CLIENTS) {
    setTimeout(createClients, BATCH_INTERVAL_IN_MS);
  }
  if (!emitInterval) {
    emitInterval = setInterval(() => {
      clients.forEach(socket => {
        socket.emit("client to server event", "hello world");
      });
    }, EMIT_INTERVAL_IN_MS);
  }
};

createClients();

const printReport = () => {
  const now = new Date().getTime();
  const durationSinceLastReport = (now - lastReport) / 1000;
  const packetsPerSeconds = (packetsSinceLastReport / durationSinceLastReport).toFixed(2);

  console.log(`client count: ${clientCount} ; average packets received per second: ${packetsPerSeconds}`);

  packetsSinceLastReport = 0;
  lastReport = now;
};

setInterval(printReport, 1000);