Before reading this article, you need to know how to create your simple chatRoom which I have shown in the previous article.
I am going to do these, step by step:
- Store each client
- Send message to the aim client
- Show that private message
- Keep showing the new message
Store each client
|
|
What we should do is to store every client in a array, in this example, I call that array sockets. Also, we need to check if the nickname has been used or not. So create another array called user in this example, this array is going to store all the nicknames. So each time,when we create another nickname, we can check is that name been used or not. What you need to know is socket.io
is to send to server, and server emits to each client.
Send message to the aim client
See in the previous code, in the client.on('chat message', function(msg, to){});
If the String “to” is not equaled to the “everyone”, then you can use sockets[to].emit()
to send message, this method is to send request to that exact client. Then only that man can receive that message XD. Looks cool 🙂
Show that private message
There is no difference in the chat.html
. Because, that request was sent to that client, other client will not receive that request, so the old chat.html
can show the information. 🙂
Keep showing the new message
Another important thing you need to pay attention is, if we have a lot of messages, each time, to view the latest message, we need to scroll down artificially…That pretty bad experience. So, what we need to do is to write some javascript code to do that automatically 🙂 sounds good.
Each time, when a new message was posted, it will run function getBottom(), and you can see the latest message 🙂
More tips:
I have write another code for the server, like to see all the messages on the console, and improve the alert message for creating a new nickname. Please check that on my github. Still the same project as the previous one, but on the oneToOne branch 🙂
You can also click this link: oneToOneChatRoom