Search code examples
node.jsserversocket.io

Remembering a client even after they disconnect nodeJS socket.io


I have a chat app and currently, the client is saving its name in a text file, this works fine for windows but mac has some weird directory settings so it makes it harder to read the text file. I'm wondering if it's possible that when a client connects my server saves their IP or some sort of constant data about the client so when the client connects again I can know who it is and assign the name accordingly.

I'm using nodeJS socket.io


Solution

  • First thing that comes to my mind is to make the client responsible for identifying itself by sending a generated UUID to server after connecting

    socket.on("connect", () => {
      const CLIENT_UUID = 'uuid';
      // Get client UUID from local storage
      let clientUuid = localStorage.getItem(CLIENT_UUID);
    
      // Check whether if this is a new client and it doesn't have UUID
      if (!clientUuid) {
        // Then generate random UUID, you'll need to implement `generateRandomUuid`
        clientUuid = generateRandomUuid();
        // Then save it to local storage
        localStorage.setItem(CLIENT_UUID, clientUuid);
      }
    
      // Then just emit the connected event
      // This will be the actual connection event as once this is emitted and received
      socket.emit('connected', {
        uuid: clientUuid
      });
    });
    

    Now on server you can handle the client based on it's UUID

    io.on('connection', (socket) => {
      // Here you handle the `connected` event
      socket.on('connected', (clientUuid) => {
        // And now you can handle this clientUuid
        const chats = getCurrentClientChats(clientUuid);
        const groups = getCurrentClientGroups(clientUuid);
    
        socket.emit('current-chats', { chats });
        socket.emit('current-groups', { groups });
      });
    });
    

    Notice that way, you'r client is now actually known on the connected event

    Same approach but probably cleaner is to send the client UUID upon connecting to the server, since it's really easy to do that with socket IO

    const socket = io("ws://example.com/my-namespace", {
      query: { clientUuid }
    });
    

    And just use it upon connection

    io.on('connection', (socket) => {
      const clientUuid = socket.handshake.query.name;
      const chats = getCurrentClientChats(clientUuid);
      const groups = getCurrentClientGroups(clientUuid);
    
      socket.emit('current-chats', { chats });
      socket.emit('current-groups', { groups });
    });