gj / fastify-ws

MIT License
55 stars 11 forks source link

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

Open satyamurthy515 opened 4 years ago

satyamurthy515 commented 4 years ago

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.