If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Great, let's start implementing sending and receiving messages in the chat room.
First, we need to modify the client-side JavaScript file chat.js
. We'll add a function called sendMessage
that will be called when the user clicks on the send button. This function will emit a message
event to the server with the message text and the current room.
javascriptCopy code
function sendMessage() {
const messageInput = document.getElementById('message-input');
const message = messageInput.value;
socket.emit('message', { text: message, room: currentRoom });
messageInput.value = '';
}
Next, we need to modify the server-side code to handle the message
event. We'll add the following code to the io.on('connection')
callback:
javascriptCopy code
socket.on('message', (data) => {
const { text, room } = data;
const message = {
text,
sender: socket.username,
timestamp: new Date().getTime(),
};
io.to(room).emit('message', message);
});
This code listens for the message
event and extracts the message text and room from the data object. It then creates a new message object with the text, the sender (which is the username of the socket), and the current timestamp. Finally, it emits the message
event to all sockets in the room.
Now we need to modify the client-side code to handle the message
event. We'll add the following code to the socket.on('connect')
callback:
javascriptCopy code
socket.on('message', (data) => {
const { text, sender, timestamp } = data;
const messageList = document.getElementById('message-list');
const messageElement = document.createElement('li');
messageElement.innerHTML = `<strong>${sender}</strong>: ${text} <span>${new Date(
timestamp
).toLocaleTimeString()}</span>`;
messageList.appendChild(messageElement);
});
This code listens for the message
event and extracts the message text, sender, and timestamp from the data object. It then creates a new list item element and sets its innerHTML to the sender, message text, and timestamp. Finally, it appends the list item to the message list.
That's it! Now users can send and receive messages in the chat room.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.