fix websocket server
This commit is contained in:
33
websocket.js
Normal file
33
websocket.js
Normal file
@ -0,0 +1,33 @@
|
||||
import WebSocket, { WebSocketServer } from "ws";
|
||||
const wss = new WebSocketServer({ noServer: true });
|
||||
|
||||
wss.on("connection", function connection(ws, req, res) {
|
||||
ws.send(`online=${wss.clients.size}`);
|
||||
setInterval(() => {
|
||||
ws.send(`online=${wss.clients.size}`);
|
||||
}, 10000);
|
||||
|
||||
ws.on("message", async function message(data, isBinary) {
|
||||
let message = Buffer.from(data).toString();
|
||||
if (message.startsWith("annc")) {
|
||||
let splitMessage = message.split(";;");
|
||||
wss.clients.forEach(client => {
|
||||
client.send(`annc;;${splitMessage[2]};;${splitMessage[3]}`);
|
||||
})
|
||||
}
|
||||
});
|
||||
|
||||
ws.on("close", () => {});
|
||||
});
|
||||
let port = 7910;
|
||||
import express from "express";
|
||||
const app = express();
|
||||
const server = app.listen(port, () => {
|
||||
console.log("Websocket server is online.");
|
||||
console.log("- http://localhost:" + port);
|
||||
});
|
||||
server.on("upgrade", (request, socket, head) => {
|
||||
wss.handleUpgrade(request, socket, head, (socket) => {
|
||||
wss.emit("connection", socket, request);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user