Socket Io
Socket Io
Socket.IO:
event.
The connection allows the client and server to send and receive data
instantly, without the overhead of new HTTP requests for every update.
Notes 1
Emit:
On:
socket.on('disconnect', () => {
Notes 2
console.log('User disconnected');
});
});
node server.js
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Client</title>
</head>
Notes 3
<body>
<input type="text" id="messageInput" placeholder="Ente
r message">
<button id="sendButton">Send</button>
<ul id="messages"></ul>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
const messageInput = document.getElementById('me
ssageInput');
const sendButton = document.getElementById('send
Button');
const messagesList = document.getElementById('me
ssages');
});
sendButton.addEventListener('click', ()=>{
const message = messageInput.value;
socket.emit('clientMessage', message);
const li = document.createElement('li');
li.textContent = `You: ${message}`;
messagesList.appendChild(li);
messageInput.value = '';
})
Notes 4
messagesList.appendChild(li);
});
</script>
</body>
</html>
Message Ordering:
Problem: Messages might not arrive in the order they were sent due to
network latencies or multiplexing.
Notes 5
Server-Side Logging:
Use console.log statements on the server to trace events and data flow.
Client-Side Logging:
Utilize browser developer tools (Network tab and Console tab) for
debugging.
Use the Console tab for logging client-side errors and debug messages.
Reduce complexity by breaking down your code into smaller parts, and
testing individual components.
Isolate the issue by removing unnecessary code, and adding them step-
by-step as you debug.
Namespaces:
Rooms:
Notes 6
Clients can join rooms to receive targeted messages (e.g., a chat room,
a game session).
Storing IDs: Use databases to store and retrieve IDs, enabling persistent
messaging even after clients disconnect.
Sending Messages:
Receiving Messages:
Messages sent from the server will be displayed in the tool's output
window.
Notes 7
Verify the events are received correctly, and that the data payload is
valid.
Disconnecting:
Notes 8