Categories
JavaScript Answers

How to set custom client ID with Socket.io and JavaScript?

Spread the love

In Socket.io, the client ID is automatically generated by the library when a client connects to the server.

However, you can create your own custom identification system by sending a custom identifier from the client to the server when the connection is established.

On the client-side (JavaScript using Socket.io) we have:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.2.0/socket.io.js"></script>
<script>
  // Connect to the Socket.io server
  const socket = io('http://localhost:3000', {
    query: {
      clientId: 'yourCustomClientIdHere' // Set your custom client ID here
    }
  });

  // Handle connection event
  socket.on('connect', () => {
    console.log('Connected to server');
  });

  // Handle other events as needed
</script>

On the server-side (Node.js using Socket.io):

const io = require('socket.io')(3000);

// Handle connection event
io.on('connection', (socket) => {
  console.log('New client connected with ID:', socket.id);

  // Access custom client ID sent from client
  const clientId = socket.handshake.query.clientId;
  console.log('Custom client ID:', clientId);
  
  // Handle other events as needed
});

In this example, on the client-side, when establishing a connection to the Socket.io server, we pass a query object to the io() function.

This query object contains the custom client ID (clientId) that we want to use.

On the server-side, when a new connection is established, Socket.io provides access to the handshake object, which contains the query parameters sent from the client.

We can access the clientId from the handshake.query object.

By sending the custom client ID as a query parameter during the connection handshake, you can effectively set a custom client ID with Socket.io.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *