fix: chat connection issues by pinging server

This commit is contained in:
2025-03-28 23:51:27 +01:00
parent 6406df0501
commit 185fc910a0
4 changed files with 38 additions and 26 deletions

View File

@@ -88,22 +88,31 @@ app.get(
});
},
onMessage(evt, ws) {
const msg = evt.data.toString();
ws.wss.clients.forEach((c) => {
const client = c as ModifiedWebSocket;
if (client.readyState === client.OPEN && client.targetUsername === ws.targetUsername) {
c.send(
JSON.stringify({
user: {
id: ws.user.id,
username: ws.personalChannel.name,
pfpUrl: ws.user.pfpUrl,
},
message: msg,
})
);
}
});
const msg = JSON.parse(evt.data.toString());
if (msg.type === 'ping') {
ws.send(
JSON.stringify({
type: 'pong',
})
);
return;
} else if (msg.type === 'message') {
ws.wss.clients.forEach((c) => {
const client = c as ModifiedWebSocket;
if (client.readyState === client.OPEN && client.targetUsername === ws.targetUsername) {
c.send(
JSON.stringify({
user: {
id: ws.user.id,
username: ws.personalChannel.name,
pfpUrl: ws.user.pfpUrl,
},
message: msg.message,
})
);
}
});
}
},
}))
);

View File

@@ -28,6 +28,7 @@ export default function ChatPanel() {
socket.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.type === 'ping' || data.type === 'pong' || !data.user) return;
setChatMessages((prev) => [...prev, data]);
} catch (e) {
console.log('Received message confirmation:', event.data);
@@ -56,7 +57,7 @@ export default function ChatPanel() {
if (!message.trim()) return;
if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) {
socketRef.current.send(message);
socketRef.current.send(JSON.stringify({ type: 'message', message }));
setMessage('');
} else {
const socket = new WebSocket(
@@ -65,12 +66,21 @@ export default function ChatPanel() {
}/api/stream/chat/ws/${username}`
);
socket.onopen = () => {
socket.send(message);
socket.send(JSON.stringify({ type: 'message', message }));
setMessage('');
};
}
};
useEffect(() => {
const interval = setInterval(() => {
if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) {
socketRef.current.send(JSON.stringify({ type: 'ping' }));
}
}, 5000);
return () => clearInterval(interval);
}, []);
return (
<div className="md:border flex flex-col w-full min-w-[350px] h-full bg-mantle">
<div ref={scrollRef} className="flex-1 p-4 overflow-y-auto flex flex-col">

View File

@@ -1,6 +1,6 @@
{
"name": "@hctv/auth",
"version": "0.0.0",
"version": "1.0.0",
"exports": {
".": {
"types": "./dist/index.d.ts",

View File

@@ -1,7 +0,0 @@
import { defineProject } from 'vitest/config'
export default defineProject({
test: {
globals: true,
},
})