Skip to content

How I can open multiple sockets with fastify-ws? #22

@satyamurthy515

Description

@satyamurthy515

Hi,

Currently, I'm running with a single socket. How I can open multiple socket connects with different routes. My single-socket example.

require('dotenv').config();
const fastify = require('fastify')({ logger: true });


fastify.register(require('fastify-cors'), {
  origin: '*',
});

fastify.register(require('fastify-ws')); // Registering websocket

function connectToSocket(ws, req) {
    console.log('Clinet got connected');
    let reqId = req.url;
 
    ws.on('message', (data) => {
      // handle messages that send from client to server
      data = JSON.stringify(data);
      console.log(data)
      ws.send(data);
    });
  }


/**
 * starting the server
 */
const start = async () => {
  try {
    await fastify.listen(process.env.APP_PORT || 8884, process.env.APP_HOST || '0.0.0.0');

    fastify.ws.on('connection', connectToSocket); // Initializing the socket controller
  } catch (error) {
    fastify.log.error(error);
    process.exit(1);
  }
};

start();

module.exports = fastify;

with this how I can open multiple socket connections. Please help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions