如何检查 Socket.IO 连接的延迟
¥How to check the latency of the Socket.IO connection
你可以通过向服务器和另一端的 回执它 发送 ping 事件来测试应用的延迟:
¥You can test the latency of your application by sending a ping event to the server and acknowledging it on the other side:
客户端
¥Client
import { io } from "socket.io-client";
const socket = io("wss://example.com");
setInterval(() => {
const start = Date.now();
socket.emit("ping", () => {
const duration = Date.now() - start;
console.log(duration);
});
}, 1000);
服务器
¥Server
import { Server } from "socket.io";
const io = new Server(3000);
io.on("connection", (socket) => {
socket.on("ping", (callback) => {
callback();
});
});
请注意,大部分延迟可能来自网络,而不是 Socket.IO(其开销与底层 WebSocket 连接大致相同)。
¥Please note that most of the latency will likely come from the network, and not Socket.IO (which has about the same overhead as the underlying WebSocket connection).
延迟可能受到很多因素的影响,其中最主要的因素显然是服务器和客户端之间的距离。
¥The latency can be impacted by a lot of factors, the major one being obviously the distance between the server and the client.
也就是说,与 WebSocket 相比,陷入 HTTP 长轮询的客户端会遇到更高的延迟,因为后者在服务器和客户端之间保持开放的 TCP 连接,并且不需要在每个请求上发送 HTTP 标头。
¥That being said, a client stuck in HTTP long-polling will see a higher latency compared to WebSocket, as the latter keeps an open TCP connection between the server and the client and does not need to send the HTTP headers on each request.
有关的:
¥Related: