loading...

Socket.io for simple chatting app

moz5691 profile image Chan Ho Ahn ・1 min read

In a basic chat application, a user first enters into the chatroom. The user is first greeted with welcome message.

Server sides does "greet message" to new entered user(s) only. The users obviously don't want to be greeted after the first welcome message.
The user start sending messages to another user but won't want to broadcast to everyone.

"io" is a Socket.IO server instance attached to an instance of listening for incoming events.

The io variable represents the group of sockets. The socket variable is only for communicating with each individual connection.

List of socket.io functions

socket.emit('message', "this is a test"); //sending to sender-client only
socket.broadcast.emit('message', "this is a test"); //sending to all clients except sender
socket.broadcast.to('game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender
socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)
socket.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid
io.emit('message', "this is a test"); //sending to all clients, include sender
io.in('game').emit('message', 'cool game'); //sending to all clients in 'game' room(channel), include sender
io.of('myNamespace').emit('message', 'gg'); //sending to all clients in namespace 'myNamespace', include sender
socket.emit(); //send to all connected clients
socket.broadcast.emit(); //send to all connected clients except the one that sent the message
socket.on(); //event listener, can be called on client to execute on server
io.sockets.socket(); //for emiting to specific clients
io.sockets.emit(); //send to all connected clients (same as socket.emit)
io.sockets.on() ; //initial connection from a client.

User input starts with simple HTML input form here.

image

There are three places you can get started with.

Client: Input from HTML form
Client: Event listener on client side with client side socket.io,
Server: Receive message and emit out to client with server side socket.io.

In the following example, "sendMessage" channel is from client to server. "receiveMessage" is from server to client. The server takes the message over sendMessage from client and send back to all clients over receiveMessage channel.

It initially may look confusing but it is pretty simple.

Client --> sendMesssage --> Server
Server <-- receiveMessage -- Server

Client side, HTML 
 id="messages" is to display broadcasted messages. 
 id ="message-form" is to hold input-field.   

<ol id="messages"></ol>
<form action="" id="message-form">
<input type="text" name="message" id="message" placeholder="enter message">
<button>Send</button>
</form>
Client side, JS
// First entered message is emitted after button click event.  This message is sent through "sendMessage" channel.  Server side will receive message through "sendMessage" channel, then, it emits to all clients connected to the server.

$('#message-form').on('submit', function(event) {
    event.preventDefault();
    socket.emit(
        'sendMessage',
    {
        from: 'User',
        text: $('#message').val()
    },
    () => {//callback function here }
  );

// Client side event listener.  It takes new messages from the server and appends it to HTML.  
socket.on('receiveMessage', message => {
    console.log('receiveMessage -- client side', message);
    const li = $('<li></li>');
    li.text(`${message.from}: ${message.text}`);
    $('#messages').append(li);
});
Server side, JS : 
// io.on from server side listens all incoming events.   Socket.emit inside io.on emits only "receiveMessage" message to all clients connected to the server.   Socket.emit only emit to sender-client while Socket.broadcast sends to every client except the sender itself.

io.on('connection', socket => {
    console.log('New user connected -- msg from server');
    /* socket.emit does Welcome message to new chatter */
    socket.emit('newMessage', chatMessage('Chatbot', 'Welcome'));
    /* socket.braodcast.emit from Admin to new user joined. */
    socket.broadcast.emit(
        'newMessage',
        generatedMessage('Chatbot', 'New User joined')
    );
     /* socket.on listens "sendMessage" from client and io.emit sends the message out to clients */
    socket.on('sendMessage', (message) => {
    console.log('Send message -- server side', message);
    io.emit('receiveMessage', chatMessage(message.from, message.text));
    });


const chatMessage = (from, text) => {
    return {
        from,
        text,
        time: new Date().getTime()
   };
};

You could add the chat history to the database such as Mongo or SQL. Plan to add it later.

Reference…
https://stackoverflow.com/questions/32674391/io-emit-vs-socket-emit

Posted on Nov 5 '18 by:

Discussion

markdown guide
 

Yea, good but then everyone can hack everyone isn't it? socket.emit in console of browser and it's done... For what to make a socket.io app since everyone can hack it? .... This technology should be disabled since is not secure.

 

Not if you use JWT auth tokens to verify each request...

 

how to send a message to specific socket id