Finally, Let's Send and Receive Message

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 396:- Finally, Let's Send and Receive Message

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.

46. Chatting Engine

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support