-
Notifications
You must be signed in to change notification settings - Fork 43
Message from Server to specified client #37
Comments
For sending message to a group of users or to a specific user you should use Pub/Sub System. // Connect socket
var cws = new ClusterWS({
url: 'localhost',
port: 80
})
// Listen on connection event
cws.on('connect', function(){
let globalChannel = cws.subscribe('Global')
// listen on messages which comes to the channel
globalChannel.watch(function(msg){
// print messages which you retrieve on the channel
console.log(msg)
})
}) This is example where you subscribe to the channel on Ok you have done with client part, now you should send message to this channel from the server: function Worker() {
const httpServer = this.httpServer
const socketServer = this.socketServer
.....
// Listen on WebSocket connection
socketServer.on('connection', (socket) => {
// Publish to the channel after 1s
setTimeout(()=>socketServer.publish('Global', 'hello world'), 1000)
})
} I have set timeout just to make sure that user will be subscribed to the channel on connect event before i publish an event Make sure that when you publish event you have users connected to the channel other vise event wont fire. Also you can With unique users you can do exactly the same thing but subscribe to the channel which is for example Also u can publish to the channel from client library check out documentation . |
This is just an example, and it mainly depends on how you want to implement your app. |
This is good. But I don't know why I need to handle the connection with a timeout: The socket is not really connected when the "on('connected')" event is emitted? |
You don't have to use time out, it is just an example. In this example user
No, it is completely connected but to subscribe you need to emit event to the server which will subscribe user to the channel. This event cause small latency. |
However if you will connect two users and remove timeout, then you may notice that your first user will receive message when your second user will be connected. In that case your first user is connected and subscribed before second user is connected. Because |
You can find some details about sending messages and pub sub in this article. “Real Time Chat with Node.js Cluster & Websocket (ClusterWS)” https://medium.com/clusterws/clusterws-chat-with-node-js-clusters-and-websockets-cb6c1224bd79 |
Hi, please can you explain me how can I send a message to a channel or a specified user from server?
I need to send to an user or many users a message or data when an event occur on server.
The text was updated successfully, but these errors were encountered: