Skip to content

Commit

Permalink
chore: update socket hook
Browse files Browse the repository at this point in the history
  • Loading branch information
ynwd committed Oct 31, 2024
1 parent c70555e commit 83cb1a7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
23 changes: 15 additions & 8 deletions modules/hook/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,25 @@ const useWebSocket = (url: string, room: string) => {
const reconnectTimeoutRef = useRef<any>(null);
const messageQueueRef = useRef<string[]>([]); // Message queue

const connectWebSocket = () => {
socketRef.current = new WebSocket(url);
function ping() {
console.log(socketRef.current);
if (socketRef.current.readyState !== WebSocket.OPEN) {
setIsConnected(false);
}
let count = 0;
const i = setInterval(() => {
if (socketRef.current?.readyState === WebSocket.OPEN) {
clearInterval(i);
}
socketRef.current?.send(JSON.stringify({ type: "ping", room }));
count++;
}, 1000);

console.log(`WebSocket connection established: ${room}`);
}

const connectWebSocket = () => {
socketRef.current = new WebSocket(url);
socketRef.current.onopen = () => {
setIsConnected(true);
socketRef.current?.send(JSON.stringify({ type: "ping", room }));
console.log(`WebSocket connection established: ${room}`);
// Send any queued messages
ping();
while (messageQueueRef.current.length > 0) {
const queuedMessage = messageQueueRef.current.shift();
if (queuedMessage) {
Expand Down
1 change: 1 addition & 0 deletions modules/socket/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export default function socketModule(s: Fastro) {
socket.onmessage = async (event) => {
const data: Data = JSON.parse(event.data);
joinRoom(ctx, socket, data.room);
console.log(event.data);
if (data.type === "ping") return;
if (data.type === "message" && data.message?.msg !== "") {
broadcastMessage(data.room, JSON.stringify(data.message));
Expand Down

0 comments on commit 83cb1a7

Please sign in to comment.