title: Socket io emitting multiple times for the same client
body: <p>I'm working on a chat application using angular 5 in the front end and nodeJS as back end and mongoDB to store the data. I integrated socket io to emit messages in real time</p>
  
  <p>The following is the code which I'm using to develop the app. Now when a user fires a message in the text box I'm emitting the message only to the user to whom the message is sent. For example, if user1 is sending the message to user2, only user2 gets the socket event and not all the other connected users. So I found a way to emit to a particular user using the socket.id</p>
  
  <p>I'm not using the same route to render all the users, I'm using different routes to different users, say "John" is the logged in user, the user can chat with other users in /message/ABC, /message/XYZ and so on. </p>
  
  <p><strong>CLIENT SIDE :</strong> </p>
  
  <p><strong>chat.component.ts</strong></p>
  
  <pre><code>ngOnInit() {
      this.loggedInUser = this.authService.getLoggedInUser();
  
      this.route.params
        .subscribe(params =&gt; {
          this.username = params['username'];
          this.receiveMessage();
        });
    }
  
  sendMessage(message) {
      const messageDetails = {
        fromUsername : this.loggedInUser.username,
        message      : (message).trim(),
        toUsername   : this.username
      };
  
      this.socketService
        .sendMessage(messageDetails);
    }
  
    receiveMessage() {
      this.socketService
        .receiveMessage()
        .subscribe(
          (message : Message) =&gt; {
            console.log(message);
        });
    }
  </code></pre>
  
  <p><strong>socket.service.client.ts</strong></p>
  
  <pre><code>import * as io from 'socket.io-client';
  
  
  private BASE_URL = AppConstants.ApiEndPoint.socketUrl;
  private socket;
  
  constructor() {
    this.socket = io("http://localhost:3000/");
  }
  
  
  sendMessage(messageDetails) {
      this.socket.emit('addMessage', messageDetails);
    }
  
    receiveMessage() {
      return new Observable(observer =&gt; {
        this.socket.on('addMessageResponse', function (message) {
          observer.next(message);
        });
        return () =&gt; {
          this.socket.disconnect();
        };
      });
    }
  </code></pre>
  
  <p><strong>SERVER SIDE :</strong> </p>
  
  <p><strong>server.js</strong></p>
  
  <p>I'm using express as middleware and passing the server instance to my socket in the server side</p>
  
  <pre><code>const http       = require('http');
  const app        = express();
  const server = http.createServer(app);
  
  require("./server/services/socket.service.server")(server);
  
  server.listen(port);
  </code></pre>
  
  <p><strong>Socket.service.server.js</strong></p>
  
  <p>On socket event <strong>addMessage</strong> , I'm adding the message to my db and then rendering the socketId of the toUser from my user model and therefore emitting only to the intended user. </p>
  
  <pre><code>module.exports = function (server) {
  
    var socketIo     = require('socket.io');
    var userModel    = require("../models/user/user.model.server");
    var messageModel = require("../models/message/message.model.server");
  
    const io = socketIo(server);
  
    io.on('connection', function(socket) {
  
      socket.on('addMessage', function (messageDetails) {
        messageModel
          .createMessage(messageDetails)
          .then(function (message) {
            userModel
              .findUserByUsername(message.toUsername)
              .then(function (user) {
                var socketId = user.socketId;
                io.to(socketId).emit('addMessageResponse', message);
              });
          });
      })
  
    });
  };
  </code></pre>
  
  <p>Now the message is emitted to the client side to the particular user. This works fine but I'm getting the message the number of times the user is connected to the client.</p>
  
  <p>For example, I logged in with a user <strong>PO</strong> I'm on route /chat/ok where ok is a connected user, ok sends a message to po. PO receives the message in the console as below</p>
  
  <p><a href="https://i.stack.imgur.com/Ixhj8.png" rel="nofollow noreferrer">screenshot 1</a></p>
  
  <p>Now I'm navigating to chat with another user and I'm on route /chat/kk where kk is another connected user.</p>
  
  <p>Now if kk sends a message to po, I'm receiving the message twice. As you can see below, I navigated to /chat/kk , I'm receiving the message twice. And similarly if I navigate to another user, I'm getting the message thrice and so on. Socket io emits a message to the user the number of times the user is getting connected to the socket. </p>
  
  <p><a href="https://i.stack.imgur.com/ltLKW.png" rel="nofollow noreferrer">Screenshot 2</a> </p>
  
  <p>I just want the normal workflow for the chat application and not emitting the message as many times the user is connected to the client. Is there a workaround ? I guess I'm making the mistake in the client side callback when I receive the response or I'm connecting multiple times for the same client. Can someone please help me out. </p>
  
  <p>Thanks !</p>