socket fix
This commit is contained in:
parent
b215904cfd
commit
0358a6025b
2 changed files with 177 additions and 150 deletions
|
|
@ -3,45 +3,55 @@ import { showError } from "@app/toast";
|
||||||
import authHtml from './chat.html?raw';
|
import authHtml from './chat.html?raw';
|
||||||
import client from '@app/api'
|
import client from '@app/api'
|
||||||
import { getUser, updateUser } from "@app/auth";
|
import { getUser, updateUser } from "@app/auth";
|
||||||
import io from 'socket.io-client';
|
import io, { Socket } from 'socket.io-client';
|
||||||
|
|
||||||
|
let __socket: Socket | undefined = undefined;
|
||||||
|
function getSocket(): Socket {
|
||||||
|
if (__socket === undefined)
|
||||||
|
__socket = io("wss://localhost:8888", {
|
||||||
|
path: "/api/chat/socket.io/",
|
||||||
|
secure: false,
|
||||||
|
transports: ["websocket"],
|
||||||
|
});
|
||||||
|
return __socket;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn {
|
function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn {
|
||||||
const socket = io("wss://localhost:8888", {
|
let socket = getSocket();
|
||||||
path: "/api/chat/socket.io/",
|
|
||||||
secure: false,
|
|
||||||
transports: ["websocket"],
|
|
||||||
});
|
|
||||||
// Listen for the 'connect' event
|
// Listen for the 'connect' event
|
||||||
socket.on("connect", () => {
|
socket.on("connect", () => {
|
||||||
console.log("I AM Connected to the server:", socket.id);
|
console.log("I AM Connected to the server:", socket.id);
|
||||||
const user = getUser()?.name;
|
const user = getUser()?.name;
|
||||||
// Ensure we have a user AND socket is connected
|
// Ensure we have a user AND socket is connected
|
||||||
if (!user || !socket.connected) return;
|
if (!user || !socket.connected) return;
|
||||||
const message = {
|
const message = {
|
||||||
type: "chat",
|
type: "chat",
|
||||||
user,
|
user,
|
||||||
token: document.cookie ?? "",
|
token: document.cookie ?? "",
|
||||||
text: " has Just ARRIVED in the chat",
|
text: " has Just ARRIVED in the chat",
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
SenderWindowID: socket.id,
|
SenderWindowID: socket.id,
|
||||||
};
|
};
|
||||||
socket.emit('message', JSON.stringify(message));
|
socket.emit('message', JSON.stringify(message));
|
||||||
});
|
});
|
||||||
// Listen for messages from the server "MsgObjectServer"
|
// Listen for messages from the server "MsgObjectServer"
|
||||||
socket.on("MsgObjectServer", (data: any) => {
|
socket.on("MsgObjectServer", (data: any) => {
|
||||||
console.log("Message Obj Recieved:", data.message);
|
console.log("Message Obj Recieved:", data.message);
|
||||||
console.log("Recieved data.message.text: ", data.message.text);
|
console.log("Recieved data.message.text: ", data.message.text);
|
||||||
console.log("Recieved data.message.user: ", data.message.user);
|
console.log("Recieved data.message.user: ", data.message.user);
|
||||||
console.log("Recieved data.message.type: ", data.message.type);
|
console.log("Recieved data.message.type: ", data.message.type);
|
||||||
console.log("Recieved data.message.token: ", data.message.token);
|
console.log("Recieved data.message.token: ", data.message.token);
|
||||||
console.log("Recieved data.message.timestamp: ", data.message.timestamp);
|
console.log("Recieved data.message.timestamp: ", data.message.timestamp);
|
||||||
// Display the message in the chat window
|
// Display the message in the chat window
|
||||||
const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement;
|
const chatWindow = document.getElementById("t-chatbox") as HTMLDivElement;
|
||||||
if (chatWindow) {
|
if (chatWindow) {
|
||||||
const messageElement = document.createElement("div");
|
const messageElement = document.createElement("div");
|
||||||
// if (getUser()?.id !== `${data.message.id}`) {
|
// if (getUser()?.id !== `${data.message.id}`) {
|
||||||
console.log('==================> HERE');
|
console.log('==================> HERE');
|
||||||
messageElement.textContent = `${data.message.user}: ${data.message.text}`;
|
messageElement.textContent = `${data.message.user}: ${data.message.text}`;
|
||||||
// } else {
|
// } else {
|
||||||
// console.log('==================>AND HERE');
|
// console.log('==================>AND HERE');
|
||||||
// messageElement.textContent = `here`;
|
// messageElement.textContent = `here`;
|
||||||
|
|
@ -49,7 +59,7 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
|
||||||
chatWindow.appendChild(messageElement);
|
chatWindow.appendChild(messageElement);
|
||||||
chatWindow.scrollTop = chatWindow.scrollHeight;
|
chatWindow.scrollTop = chatWindow.scrollHeight;
|
||||||
}
|
}
|
||||||
console.log("Getuser():", getUser());
|
console.log("Getuser():", getUser());
|
||||||
});
|
});
|
||||||
|
|
||||||
type Providers = {
|
type Providers = {
|
||||||
|
|
@ -62,10 +72,10 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
|
||||||
// function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn {
|
// function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn {
|
||||||
|
|
||||||
setTitle('Chat Page');
|
setTitle('Chat Page');
|
||||||
// Listen for the 'connect' event
|
// Listen for the 'connect' event
|
||||||
return {
|
return {
|
||||||
|
|
||||||
html: authHtml, postInsert: async (app) => {
|
html: authHtml, postInsert: async (app) => {
|
||||||
const sendButton = document.getElementById('b-send') as HTMLButtonElement;
|
const sendButton = document.getElementById('b-send') as HTMLButtonElement;
|
||||||
const chatWindow = document.getElementById('t-chatbox') as HTMLDivElement;
|
const chatWindow = document.getElementById('t-chatbox') as HTMLDivElement;
|
||||||
const sendtextbox = document.getElementById('t-chat-window') as HTMLButtonElement;
|
const sendtextbox = document.getElementById('t-chat-window') as HTMLButtonElement;
|
||||||
|
|
@ -74,7 +84,7 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
|
||||||
const bconnected = document.getElementById('b-help') as HTMLButtonElement;
|
const bconnected = document.getElementById('b-help') as HTMLButtonElement;
|
||||||
const username = document.getElementById('username') as HTMLDivElement;
|
const username = document.getElementById('username') as HTMLDivElement;
|
||||||
|
|
||||||
const value = await client.chatTest();
|
const value = await client.chatTest();
|
||||||
if (value.kind === "success") {
|
if (value.kind === "success") {
|
||||||
console.log(value.payload);
|
console.log(value.payload);
|
||||||
} else if (value.kind === "notLoggedIn") {
|
} else if (value.kind === "notLoggedIn") {
|
||||||
|
|
@ -84,34 +94,35 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const addMessage = (text: string) => {
|
const addMessage = (text: string) => {
|
||||||
if (!chatWindow) return;
|
if (!chatWindow) return;
|
||||||
const messageElement = document.createElement("div");
|
const messageElement = document.createElement("div");
|
||||||
messageElement.textContent = text;
|
messageElement.textContent = text;
|
||||||
chatWindow.appendChild(messageElement);
|
chatWindow.appendChild(messageElement);
|
||||||
chatWindow.scrollTop = chatWindow.scrollHeight;
|
chatWindow.scrollTop = chatWindow.scrollHeight;
|
||||||
};
|
console.log(`Added new message: ${text}`)
|
||||||
|
};
|
||||||
|
|
||||||
// Send button
|
// Send button
|
||||||
sendButton?.addEventListener("click",() => {
|
sendButton?.addEventListener("click", () => {
|
||||||
if (sendtextbox && sendtextbox.value.trim()) {
|
if (sendtextbox && sendtextbox.value.trim()) {
|
||||||
const msgText = sendtextbox.value.trim();
|
const msgText = sendtextbox.value.trim();
|
||||||
addMessage(msgText);
|
addMessage(msgText);
|
||||||
const user = getUser();
|
const user = getUser();
|
||||||
if (user && socket?.connected) {
|
if (user && socket?.connected) {
|
||||||
const message = {
|
const message = {
|
||||||
type: "chat",
|
type: "chat",
|
||||||
user: user.name,
|
user: user.name,
|
||||||
token: document.cookie,
|
token: document.cookie,
|
||||||
text: msgText,
|
text: msgText,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
SenderWindowID: socket.id,
|
SenderWindowID: socket.id,
|
||||||
};
|
};
|
||||||
socket.send(JSON.stringify(message));
|
socket.send(JSON.stringify(message));
|
||||||
}
|
}
|
||||||
sendtextbox.value = "";
|
sendtextbox.value = "";
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
// Clear Text button
|
// Clear Text button
|
||||||
|
|
@ -127,13 +138,12 @@ function handleChat(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
|
||||||
if (chatWindow) {
|
if (chatWindow) {
|
||||||
addMessage('@list - lists all connected users in the chat');
|
addMessage('@list - lists all connected users in the chat');
|
||||||
await socket.emit('list');
|
await socket.emit('list');
|
||||||
|
|
||||||
socket.on('listObj', (list: string) => {
|
|
||||||
console.log('List chat clients connected ', list);
|
|
||||||
addMessage(list);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
socket.on('listObj', (list: string) => {
|
||||||
|
console.log('List chat clients connected ', list);
|
||||||
|
addMessage(list);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
// Enter key to send message
|
// Enter key to send message
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ import { Server, Socket } from 'socket.io';
|
||||||
declare const __SERVICE_NAME: string;
|
declare const __SERVICE_NAME: string;
|
||||||
|
|
||||||
// Global map of clients
|
// Global map of clients
|
||||||
const clientChat = new Map<string, string>(); // key = client name, value = socket
|
const clientChat = new Map<string, string>(); // key = client name, value = socket
|
||||||
|
|
||||||
// @ts-expect-error: import.meta.glob is a vite thing. Typescript doesn't know this...
|
// @ts-expect-error: import.meta.glob is a vite thing. Typescript doesn't know this...
|
||||||
const plugins = import.meta.glob('./plugins/**/*.ts', { eager: true });
|
const plugins = import.meta.glob('./plugins/**/*.ts', { eager: true });
|
||||||
|
|
@ -73,71 +73,83 @@ declare module 'fastify' {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onReady(fastify: FastifyInstance) {
|
async function onReady(fastify: FastifyInstance) {
|
||||||
|
|
||||||
|
|
||||||
function connectedUser(io?: Server, target?: string): number {
|
function connectedUser(io?: Server, target?: string): number {
|
||||||
let count = 0;
|
let count = 0;
|
||||||
const seen = new Set<string>(); // <- only log/count unique usernames
|
const seen = new Set<string>();
|
||||||
|
// <- only log/count unique usernames
|
||||||
|
|
||||||
for (const [socketId, username] of clientChat) {
|
for (const [socketId, username] of clientChat) {
|
||||||
// Basic sanity checks
|
// Basic sanity checks
|
||||||
if (typeof socketId !== "string" || socketId.length === 0) {
|
if (typeof socketId !== 'string' || socketId.length === 0) {
|
||||||
clientChat.delete(socketId);
|
clientChat.delete(socketId);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (typeof username !== "string" || username.length === 0) {
|
if (typeof username !== 'string' || username.length === 0) {
|
||||||
clientChat.delete(socketId);
|
clientChat.delete(socketId);
|
||||||
continue;
|
continue;
|
||||||
}
|
|
||||||
|
|
||||||
// If we have the io instance, attempt to validate the socket is still connected
|
|
||||||
if (io && typeof io.sockets?.sockets?.get === "function") {
|
|
||||||
const s = io.sockets.sockets.get(socketId) as Socket | undefined;
|
|
||||||
// If socket not found or disconnected, remove from map and skip
|
|
||||||
if (!s || s.disconnected) {
|
|
||||||
clientChat.delete(socketId);
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip duplicates (DO NOT delete them — just don't count)
|
// If we have the io instance, attempt to validate the socket is still connected
|
||||||
if (seen.has(username)) {
|
if (io && typeof io.sockets?.sockets?.get === 'function') {
|
||||||
continue;
|
const s = io.sockets.sockets.get(socketId) as
|
||||||
}
|
| Socket
|
||||||
// socket exists and is connected
|
| undefined;
|
||||||
seen.add(username);
|
// If socket not found or disconnected, remove from map and skip
|
||||||
|
if (!s || s.disconnected) {
|
||||||
|
clientChat.delete(socketId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip duplicates (DO NOT delete them — just don't count)
|
||||||
|
if (seen.has(username)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// socket exists and is connected
|
||||||
|
seen.add(username);
|
||||||
|
count++;
|
||||||
|
// console.log(color.green,"count: ", count);
|
||||||
|
console.log(color.yellow, 'Client:', color.reset, username);
|
||||||
|
|
||||||
|
const targetSocketId: any = target;
|
||||||
|
io.to(targetSocketId).emit('listObj', username);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
color.yellow,
|
||||||
|
'Chat Socket ID:',
|
||||||
|
color.reset,
|
||||||
|
socketId,
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no io provided, assume entries in the map are valid and count them.
|
||||||
count++;
|
count++;
|
||||||
// console.log(color.green,"count: ", count);
|
console.log(
|
||||||
console.log(color.yellow, "Client:", color.reset, username);
|
color.red,
|
||||||
|
'Client (unverified):',
|
||||||
|
color.reset,
|
||||||
|
username,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
color.red,
|
||||||
|
'Chat Socket ID (unverified):',
|
||||||
|
color.reset,
|
||||||
|
socketId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const targetSocketId: any = target;
|
return count;
|
||||||
io.to(targetSocketId).emit("listObj", username);
|
|
||||||
|
|
||||||
|
|
||||||
console.log(color.yellow, "Chat Socket ID:", color.reset, socketId);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If no io provided, assume entries in the map are valid and count them.
|
|
||||||
count++;
|
|
||||||
console.log(color.red, "Client (unverified):", color.reset, username);
|
|
||||||
console.log(color.red, "Chat Socket ID (unverified):", color.reset, socketId);
|
|
||||||
}
|
|
||||||
|
|
||||||
return count;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function broadcast(data: ClientMessage, sender?: string) {
|
function broadcast(data: ClientMessage, sender?: string) {
|
||||||
fastify.io.fetchSockets().then((sockets) => {
|
fastify.io.fetchSockets().then((sockets) => {
|
||||||
|
|
||||||
for (const s of sockets) {
|
for (const s of sockets) {
|
||||||
if (s.id !== sender) {
|
if (s.id !== sender) {
|
||||||
|
// Send REAL JSON object
|
||||||
// Send REAL JSON object
|
const clientName = clientChat.get(s.id) || null;
|
||||||
const clientName = clientChat.get(s.id) || null;
|
if (clientName !== null) {
|
||||||
if (clientName !== null) {
|
s.emit('MsgObjectServer', { message: data });
|
||||||
s.emit('MsgObjectServer', { message: data });
|
}
|
||||||
}
|
|
||||||
console.log(' Target window socket ID:', s.id);
|
console.log(' Target window socket ID:', s.id);
|
||||||
console.log(' Target window ID:', [...s.rooms]);
|
console.log(' Target window ID:', [...s.rooms]);
|
||||||
console.log(' Sender window ID:', sender ? sender : 'none');
|
console.log(' Sender window ID:', sender ? sender : 'none');
|
||||||
|
|
@ -148,7 +160,12 @@ async function onReady(fastify: FastifyInstance) {
|
||||||
|
|
||||||
fastify.io.on('connection', (socket: Socket) => {
|
fastify.io.on('connection', (socket: Socket) => {
|
||||||
socket.on('message', (message: string) => {
|
socket.on('message', (message: string) => {
|
||||||
console.info(color.blue, 'Socket connected!', color.reset, socket.id);
|
console.info(
|
||||||
|
color.blue,
|
||||||
|
'Socket connected!',
|
||||||
|
color.reset,
|
||||||
|
socket.id,
|
||||||
|
);
|
||||||
console.log(
|
console.log(
|
||||||
color.blue,
|
color.blue,
|
||||||
'Received message from client',
|
'Received message from client',
|
||||||
|
|
@ -156,7 +173,6 @@ async function onReady(fastify: FastifyInstance) {
|
||||||
message,
|
message,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
const obj: ClientMessage = JSON.parse(message) as ClientMessage;
|
const obj: ClientMessage = JSON.parse(message) as ClientMessage;
|
||||||
clientChat.set(socket.id, obj.user);
|
clientChat.set(socket.id, obj.user);
|
||||||
console.log(
|
console.log(
|
||||||
|
|
@ -167,10 +183,14 @@ async function onReady(fastify: FastifyInstance) {
|
||||||
);
|
);
|
||||||
// Send object directly — DO NOT wrap it in a string
|
// Send object directly — DO NOT wrap it in a string
|
||||||
broadcast(obj, obj.SenderWindowID);
|
broadcast(obj, obj.SenderWindowID);
|
||||||
console.log(color.red, 'connected in the Chat :', connectedUser(fastify.io), color.reset);
|
console.log(
|
||||||
|
color.red,
|
||||||
|
'connected in the Chat :',
|
||||||
|
connectedUser(fastify.io),
|
||||||
|
color.reset,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
socket.on('testend', (sock_id_cl: string) => {
|
socket.on('testend', (sock_id_cl: string) => {
|
||||||
console.log('testend received from client socket id:', sock_id_cl);
|
console.log('testend received from client socket id:', sock_id_cl);
|
||||||
});
|
});
|
||||||
|
|
@ -178,32 +198,29 @@ async function onReady(fastify: FastifyInstance) {
|
||||||
socket.on('list', () => {
|
socket.on('list', () => {
|
||||||
console.log(color.red, 'list activated', color.reset, socket.id);
|
console.log(color.red, 'list activated', color.reset, socket.id);
|
||||||
connectedUser(fastify.io, socket.id);
|
connectedUser(fastify.io, socket.id);
|
||||||
|
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
socket.on('disconnecting', (reason) => {
|
||||||
|
const clientName = clientChat.get(socket.id) || null;
|
||||||
|
console.log(
|
||||||
socket.on("disconnecting", (reason) => {
|
color.green,
|
||||||
|
`Client disconnecting: ${clientName} (${socket.id}) reason:`,
|
||||||
const clientName = clientChat.get(socket.id) || null;
|
reason,
|
||||||
console.log(color.green, `Client disconnecting: ${clientName} (${socket.id}) reason:`, reason);
|
);
|
||||||
if (reason === 'transport error') return;
|
if (reason === 'transport error') return;
|
||||||
|
|
||||||
|
|
||||||
if (clientName !== null) {
|
if (clientName !== null) {
|
||||||
const obj = {
|
const obj = {
|
||||||
type: "chat",
|
type: 'chat',
|
||||||
user: clientName,
|
user: clientName,
|
||||||
token: "",
|
token: '',
|
||||||
text: `LEFT the chat`,
|
text: 'LEFT the chat',
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
SenderWindowID: socket.id,
|
SenderWindowID: socket.id,
|
||||||
};
|
};
|
||||||
|
|
||||||
broadcast(obj, obj.SenderWindowID);
|
broadcast(obj, obj.SenderWindowID);
|
||||||
// clientChat.delete(obj.user);
|
// clientChat.delete(obj.user);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue