I created a Websocket server using Bun.serve()
. In this server, when a new client connects, I send it 1 million packets with a for loop. But these packets are interrupted. Hundreds of thousands of packets are not sent to the client. I used the ws
package from NPM instead of Bun’s Websocket and the problem is solved. How can Bun, which claims to be a much faster Websocket server than ws, experience packet loss? Is there a solution to this or should I use ws
until this problem is noticed?
server.js
const Bun = require("bun");
Bun.serve({
fetch(req, server) {
if (server.upgrade(req)) return;
return new Response("Only WebSocket connections are supported.", {status: 400});
},
websocket: {
open(socket) {
const start = performance.now();
for (let i = 0; i < 1_000_000; i++) socket.send(JSON.stringify({"type": "MESSAGE_CREATE", "data": {"content": i}}));
const end = performance.now();
const duration = end - start;
console.log(duration.toFixed(2) + " ms");
},
close(socket) {
console.log("Client disconnected");
},
error(socket, error) {
console.error("WebSocket error:", error);
}
},
port: 8080,
reusePort: true
});
client.js
const WebSocket = require("ws");
const ws = new WebSocket("ws://localhost:8080");
var count = 0;
var start_date;
ws.on("message", message => {
count++;
if (count === 1) console.log(message.toString() + " 0 ms"), start_date = Date.now();
if (count >= 999_990) console.log(message.toString() + " " + (Date.now() - start_date) + " ms");
});
setInterval(() => console.log(count), 5000);
Solution without packet loss but with ws
library.
server.js
const http = require("http");
const WebSocket = require("ws");
const Server = http.createServer();
const ws = new WebSocket.Server({server: Server});
ws.on("connection", socket => {
const start = performance.now();
for (let i = 0; i < 1_000_000; i++) socket.send(JSON.stringify({"type": "MESSAGE_CREATE", "data": {"content": i}}));
const end = performance.now();
const duration = end - start;
console.log(duration.toFixed(2) + " ms");
})
Server.listen(8080);