DEV Community

Chan Ho Ahn
Chan Ho Ahn

Posted on

Socket.io for simple chatting app

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

Top comments (5)

Collapse
 
lethanhvietctt5 profile image
Le Thanh Viet

I have learned about ReactJS and Socket recently and written an video call and chat app using ReactJS and Socket .Here is my source code: github.com/lethanhvietctt5/video-c.... I hope it can help you guys to build a video chat app.

Collapse
 
sahilatahar profile image
Sahil Atahar

Nice, I have build a Realtime code editor project using socket.io called Code-Sync.

🔮 Features of the project:

  • 💻 Real-time collaboration on code editing across multiple files
  • 🚀 Unique room generation with room ID for collaboration
  • 🌈 Syntax highlighting for various file types with auto-language detection
  • 💡 Auto suggestion based on programming language
  • ⏱️ Instant updates and synchronization of code changes across all files
  • 📣 Notifications for user join and leave events
  • 🎨 Multiple themes for personalized coding experience
  • 🌍 Comprehensive language support for versatile programming
  • 🔠 Option to change font size and font family
  • 👥 User presence list of users currently in the collaboration session, including online/offline status indicators
  • 📁 Open, edit, save, and delete file functionalities
  • 💾 Option to download files edited within the collaboration session
  • 💬 Group chatting allows users to communicate in real-time while working on code.
  • 🎩 Real-time tooltip displaying users currently editing
  • 🚀 Code Execution: Users can execute the code directly within the collaboration environment, providing instant feedback and results.
Collapse
 
lifeowner profile image
lifeowner

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.

Collapse
 
bijanmarkes profile image
Bijan Markes

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

Collapse
 
kururu95 profile image
kururu

how to send a message to specific socket id