douyin-live-danmu/apps/demo/app.js

35 lines
975 B
JavaScript
Raw Normal View History

2024-01-30 20:40:12 +08:00
import { WebSocketServer } from "ws";
import { pool, insert } from "./crud.js";
const getTime = () => `[${new Date().toLocaleTimeString()}]`;
const wss = new WebSocketServer({ port: 9527 });
wss.on("connection", function connection(ws) {
console.log("客户端连接成功");
ws.on("message", function message(data) {
let message = JSON.parse(data.toString());
console.log(message);
switch (message.action) {
case "message":
console.log(
getTime(),
message.message.user_nickName + ":" + message.message.msg_content
);
insert(pool, { ...message.message, create_time: getTime() });
break;
case "join":
console.log(
getTime(),
message.message.user_nickName + ":" + message.message.msg_content
);
break;
}
wss.clients.forEach((cen) => {
cen.send(JSON.stringify(message));
});
});
});
console.log("打开-> http://127.0.0.1:9527");