-
Notifications
You must be signed in to change notification settings - Fork 10
Client to Client Communication
Basically there are 2 ways to communicate between clients and both the ways uses Pub/Sub System.
The first way does not include any server coding (all your logic is saved in front-end application). You subscribe
, watch
and publish
from the front-end application.
socket.on('connect', () => {
// Subscribe to the channel (can be any channels you want)
channel = socket.subscribe('any-channel-name')
// Listen on messages in that channel
channel.watch((message) => {
// Execute code when receive any messages on the channel
})
// Publish any message you want
channel.publish('any-message-you-want')
})
Second way is publishing messages from the server, and not from the front-end application.
// Client
socket.on('connect', () => {
socket.send('event-name', 'my message')
})
// Server
socketServer.on('connection', (socket) => {
socket.on('event-name', (message) => {
socketServer.publish('The Channel you want to publish', message)
})
})
as you can see in second example all logic of publish
moved to the server, where you can make many things before publishing, also second method gives you ability to publish messages even if client is not subscribed to the channel.
The last part i wanted to mention about is specific client communication, like what if you want to send message to a specific client, and not to the group. That is pretty easy too, you just have to create unique channel (can be user_id) for each client and use onsubscribe
middleware (check server documentation) on the server to allow only this particular client to subscribe to this unique channel.
Then you can use second method to send message to the client from another client.
// Client
socket.on('connect', () => {
socket.send('send-to-friend', {receiverId: 'xyz', message: 'Hello'})
})
// Server
socketServer.on('connection', (socket) => {
socket.on('send-to-friend', (message) => {
socketServer.publish(message.receiverId, message.message)
})
})
How you get receiverId
on front-end you have to figure that out by your self as there many different ways of doing it.
💥 We would really appreciate if you give us stars ⭐ (on all our repositories):
For you to give the stars ⭐ is not hard, but for us, it is a huge motivation to work harder and improve the project. Thank you very much 😄.
1. Home
2. Installation and Configuration
5. Client to Client Communication
Other languages will be added later