I am trying to learn how to make a chat App using socket.io
,ejs
,nodejs
...
So I am basically studying a code from the following repo: https://github.com/ngrt/simpleChatApp
The folder structure is like
simpleChatApp
(the parent folder)
-views(contains index.ejs
)
-public (contains style.css
and chat.js
)
-app.js (the file which has the server code )
app.js has app.use(express.static('public'))
so public works as root
Now the problem is in chat.js ( which contains the client-side backend)
below picture is a part of chat.js
send_message.click(function(){
socket.emit('new_message', {message : message.val()})
})
//Listen on new_message
socket.on("new_message", (data) => {
feedback.html('');
message.val('');
chatroom.append("<p class='message'>" + data.username + ": " + data.message + "</p>")
})
In the emit part we only sent a message field .....whereas in the socket.on part we used data.username() ...Now from what I think data is basically the object we sent in emit ....which didn't contain any username ..so how can it use it ..cause its a working repo so the code is correct ..but I can't understand why
The message received by client's socket.on
is emitted by nodejs's emit (and not client's one as in you code). This is node js
's code, where username is appended:
socket.on('new_message', (data) => {
//broadcast the new message
io.sockets.emit('new_message', {message : data.message, username : socket.username});
})
In general in your example multiple clients are listening to the server message and server is listening to each client's emit. Username is stored by the server on each new socket
object. Initial value on connect is 'Anonymous' and is updated on change_username
event:
socket.on('change_username', (data) => {
socket.username = data.username
})
First send_mesasage emit in chat.js
is received by app.js
and is immediately emitted to all connected clients (including the sender).
Server adds a user name to this emit (which was stored in socket
object by server).
Then, each client receives this emit (which already has a username). All connected clients then print received message and username