WebSocket with cluster


#1

I followed the example in the main page from Introduction link

  1. Installing adonis install @adonisjs/websocket.
  2. Add '@adonisjs/websocket/providers/WsProvider' to providers in start/app.js.
  3. Add .wsServer() into server.js.
  4. Add cluster support into start/server.js like in the example.
  5. Add Ws.channel('chat', 'ChatController') to start/socket.js.
  6. Create Chat controller adonis make:controller Chat --type=ws.
  7. Create chat.edge and style.css with their code provide in this page.
  8. Create public/chat.js with its code provide in the same page.

My point is:
when I tested with clusters, each socket from different cluster don’t send a message to others cluster of diferent pid.

How I tested it:
I try to test if with cluster mode works, I print the process id in chat controller, this way is easy to see which cluster I’m in when i enter to /chat, and when the chat was in different pid I try to send a message, and it didn’t work, it works when is the same cluster node.

I’m new in Adonisjs and new in nodejs

UPDATE:
this is the code of chatcontroller

'use strict'

class ChatController {
  constructor ({ socket, request }) {
    console.log(process.pid)
    this.socket = socket
    this.request = request
  }

  onMessage (message) {
    console.log(process.pid)
    this.socket.broadcastToAll('message', message)
  }
}

module.exports = ChatController

#2

What’s the code you use to send the message?


#3

check the update


#4

What you are doing is using the socket instance to receive messages from other process.

Whereas the socket instance is a connection with the client and not another process.

There is a pub/sub that automatically sends messages to the clients connected on another process. Note: Messages are delivered to connected clients and not the server


#5

I find a different pub/sub, that is refer to redis in the documentation from Adonisjs, but I find another pub/sub require('@adonisjs/websocket/clusterPubSub')() refer to websocket that say

When running a Node.js cluster, you need to write one line of code inside the master node to hook the pub/sub between workers.

and is this code from server.js

const cluster = require('cluster')

if (cluster.isMaster) {
  for (let i=0; i < 4; i ++) {
    cluster.fork()
  }
  require('@adonisjs/websocket/clusterPubSub')()
  return
}

const { Ignitor } = require('@adonisjs/ignitor')
new Ignitor(require('@adonisjs/fold'))
 .appRoot(__dirname)
 .wsServer()
 .fireHttpServer()
 .catch(console.error) 

but in chatController I don’t know how to send a message to other workers(clusters), can you help me a little more, please.


#6

Redis has nothing to do with this.

When you broadcast the message, then it is automatically sent to all the clients connected on all the PID’s.

Checkout this for more info