docs(code): document websocket flow
This commit is contained in:
@@ -16,6 +16,7 @@ let socket = null;
|
||||
let currentUser = '';
|
||||
let currentRoom = '';
|
||||
|
||||
// Persist the last used identity locally so refreshing the page is convenient.
|
||||
usernameInput.value = localStorage.getItem('chat_username') || '';
|
||||
roomInput.value = localStorage.getItem('chat_room') || 'عمومی';
|
||||
|
||||
@@ -48,6 +49,8 @@ function formatTime(timestamp) {
|
||||
if (!timestamp) return '';
|
||||
const date = new Date(timestamp);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
|
||||
// The server stores UTC timestamps; the browser formats them for the user.
|
||||
return date.toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
@@ -108,6 +111,7 @@ function connect() {
|
||||
const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
const wsUrl = `${wsProtocol}://${window.location.host}/ws/${encodeURIComponent(currentRoom)}/${encodeURIComponent(currentUser)}`;
|
||||
|
||||
// Opening this object starts the HTTP Upgrade handshake automatically.
|
||||
socket = new WebSocket(wsUrl);
|
||||
|
||||
socket.addEventListener('open', () => {
|
||||
@@ -120,6 +124,7 @@ function connect() {
|
||||
socket.addEventListener('message', (event) => {
|
||||
const payload = JSON.parse(event.data);
|
||||
|
||||
// Presence messages update the sidebar; chat/system messages go to the feed.
|
||||
if (payload.type === 'presence') {
|
||||
updateUsers(payload.users || []);
|
||||
return;
|
||||
@@ -159,6 +164,7 @@ messageForm.addEventListener('submit', (event) => {
|
||||
const content = messageInput.value.trim();
|
||||
if (!content || !socket || socket.readyState !== WebSocket.OPEN) return;
|
||||
|
||||
// The server accepts JSON messages and broadcasts the content to the room.
|
||||
socket.send(JSON.stringify({ content }));
|
||||
messageInput.value = '';
|
||||
messageInput.focus();
|
||||
|
||||
Reference in New Issue
Block a user