i try create a multi channel depending on the path with nodejs in the same port.
For exemple (my port is 8080) :
wwww.exemple.com:8080/channel/1
wwww.exemple.com:8080/channel/2
wwww.exemple.com:8080/channel/3
wwww.exemple.com:8080/channel/4
Each url path channel corresponds to a channel redis
For exemple (channel-X) :
var channel = 'channel-X'
getRedis.subscribe(channel);
but I do not know how to link the channel and repeat the url.
here is my code to the current time.
socket.on('connection', function(client) {
const getRedis = redis.createClient();
const sendRedis = redis.createClient();
getRedis.subscribe('channel-1');
getRedis.on("message", function(channel, message) {
client.send(message);
});
client.on('message', function(msg) {
sendRedis.publish('channel-1',msg);
});
client.on('disconnect', function() {
getRedis.quit();
sendRedis.quit();
});
});
I am a bit in the fog all proposals will be welcome:)
You cannot link your channel name to your socket.io. Because socket.io client only carry latest user infor only.
Solution 1:
You can pass the channel name from client side.
//Client side
var socket = new io.Socket();
socket.on('connect', function() {
socket.send({ChannelName:'channel-X',Message:'HI !!'});
});
//Server side
socket.on('connection', function(client) {
const getRedis = redis.createClient();
getRedis.on("message", function(channel, message) {
client.send(message);
});
client.on('message', function(msg) {
//Assume the input msg is JSON structure {ChannelName:'channel-X',Message:'HI !!'}
var data = JSON.parse(msg);
getRedis.subscribe(data.ChannelName);
});
});
Solution 2:
Use session store to store/get the channel name by socket session id.
Problem : I not understand what you need "url to managed subscriptions to channels repeat"
What is channels repeat ?
Related
The code below works fine by broadcasting typing notification and chat messages to all connected users.
Here is what I want: How do I send typing notification and chat messages only to users connected to a particular room
say Room1, Room2 etc.
here is the code
index.html
var socket = io();
var user = 'nancy';
function submitfunction(){
var from = 'nancy';
var message = 'hello Nancy';
socket.emit('chatMessage', from, message);
}
function notifyTyping() {
var user = 'nancy'
socket.emit('notifyUser', user);
}
socket.on('chatMessage', function(from, msg){
//sent message goes here
});
socket.on('notifyUser', function(user){
$('#notifyUser').text(nancy is typing ...');
setTimeout(function(){ $('#notifyUser').text(''); }, 10000);
});
server.js
var io = require('socket.io')(http);
io.on('connection', function(socket){
socket.on('chatMessage', function(from, msg){
io.emit('chatMessage', from, msg);
});
socket.on('notifyUser', function(user){
io.emit('notifyUser', user);
});
});
am using npm installed socket.io ^2.3.0
To send the message to a specific room, you will have to create and join a room with roomId. Below is a basic code snippet
//client side
const socket = io.connect();
socket.emit('create', 'room1');
// server side code
socket.on('create', function(room1) {
socket.join(room1);
});
To emit data to a specific room
// sending to all clients in 'room1'except sender
socket.to('room1').emit('event',data);
// sending to all clients in 'room1' room, including sender
io.in('room1').emit('event', 'data');
You can follow this question for details on how to create a room?
Creating Rooms in Socket.io
This emit cheat sheet might also be useful:
https://github.com/socketio/socket.io/blob/master/docs/emit.md
The nodejs (10.16) and express (4.16) backend server (server) runs with socket.io 2.2.0 for a chat app. The message received on the server will be broadcast to the clients connecting to the same room (channel). The socket.io instance is created in index.js:
const io = require('socket.io')(server);
io.on('connection', async (socket) => {
socket.my_id = "";
console.log("socket.id : ", socket.id);
app.set("socket", socket);
console.log("Socketio server is initialized");
//disconnect
socket.on('disconnect', async function() {
//if (socket.my_id) helper.RemoveSocketUser(user.fort_token, socket.my_id);
console.log('disconnected event');
});
});
server.listen(port, () => {};
Then after a message is saved on the server, the socket is used to broadcast to the clients in the same room.
try {
await msg.save();
msg.user_name = req.user.name;
msg.user_avatar = req.user.user_data.avatar;
const io = req.app.get("io");
const socket = req.app.get('socket');
const room = msg.event_id.toString();
socket.my_id = req.user.id;
socket.join(room);
console.log("socket in new message : ", socket.id);
console.log("msg before broadcast : ", msg.data.msg_body);
io.to(room).emit("event message", msg);
return res.status(200).send(req.body.data.msg_body);
} catch (err) {
console.log("Error in saving/braodcasting a new message", err);
return res.status(400).send(err.message);
};
From the console output, the socket.id is the same for 2 clients connecting to the same room and chatting. Here is a output for Android emulator running on port 8081:
socket in new message : b0po9l6hGZUi9xVDAAAE
msg before broadcast : 8081
Here is another android emulator running on port 9090:
socket in new message : b0po9l6hGZUi9xVDAAAE
msg before broadcast : 9090
However the socket.id on clients side is not the same. What causes the server using the same socket.id for 2 clients?
What you are trying to do is accessing socket object stored in express,
which will update socket object every time new socket get connected that's why you are getting same socket id [ last connected ].
to access specific socket from outside the io connection scope, you have to get the socket instance from io object.
you need to store socket id somewhere in database or memory like redis.
const socketid = `get user's latest connected socket id.`
cont socket = io.sockets.sockets[socketid];
socket.emit('req', { data: "something"})
I created application in Ionic 4, and for backend I use Lumen. Application should have chat page and in that purpose I add Redis, Socket.io and nodejs. I successfully created public room, and chat between users in that room works. Problem is how to send private message for user, how to initialize users for their private room.
This is how I created public room:
constructor(private socket: Socket) {
this.getMessages().subscribe(message => {
this.messages.push(message);
});
}
getMessages() {
const observable = new Observable(observer => {
this.socket.on('message', (data) => {
observer.next(data);
});
});
return observable;
}
I send message from Lumen application and Redis:
public function sendMessage()
{
$redis = Redis::Connection();
$sendMessage = json_encode(['user' => 'John Doe', 'text' => 'Some message, text', 'channel' => 'message']);
$redis->publish('add-message', $sendMessage);
}
And my node server is:
let express = require('express');
let app = express();
let http = require('http').Server(app);
let redis = require('redis');
let client = redis.createClient("redis://127.0.0.1:6379");
let io = require('socket.io')(http);
app.use('/', express.static('www'));
http.listen(3000, '192.168.10.10', function(){
console.log('listening on *:3000');
});
client.on('message', function(chan, msg) {
let data = JSON.parse(msg);
io.sockets.emit(data.channel, msg);
});
client.subscribe('add-message');
Bottom line everyone who is subscribed on 'message' channel will get message. Problem is that I subscribe user on channel when came to chat page. I don't know how to subscribe user, and when, on channel where some another user send him message.Also how that sender user to create new room, I suppose to use id of users for room name (per instance user1_user2).
Does anyone know how I can solve this problem? I don't know even I described well.
Thanks in advance
I want my client-side code to send the server the user's userid when establishing the connection, then i want the server to check the database for new messages for each user that is connecting, and send the user the number of new messages it has when new messages are available.
My client-side code:
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
socket.emit('userid', '1');
});
socket.on('new_message', function (data) {
var number_of_messages= "<p>"+data.number+"</p>";
$('#container').html(number_of_messages);
});
My server-side code:
io.sockets.on( 'userid', function (data) {
console.log('userid: '+data);
});
My problem is that the above code is not working: the userid is never received by the serverside and the on('userid') is never called.
My question is how to know which socket sent this user id and how to send to only this specific socket a certain message.
I have solved the problem by saving the clients socket and their id into a global array. this is not a good solution but it works; I know there are rooms and namespaces but I never used it..
socket.io namespaces and rooms
however,
(I used express)
client:
var socket = io.connect('http://localhost:3000',{reconnection:false});
socket.once('connect', function() {
socket.emit('join', '#{id}');
};
server:
var clients = [];
app.io.on('connection', function(socket) {
socket.on('join', function(data) {
clients.push({
ws: socket,
id: data
});
//retrive the messages from db and loop the clients array
//and socket.send(things)
}
}
I am trying to implement a functionality wherein when a user is viewing a page, he should be automatically subscribed a Redis channel unique to that user. And all message published to that Redis channel should be received by the client side.
Below is by client side code,
var socket = io.connect('localhost:5000');
socket.on('connect', function(){
socket.emit("subscribe",$("#app_id").text());
});
socket.on('message', function(message) {
$("#lst").append("<li>" + message + "</li>")
});
And on the nodejs server, I have below code,
var client = redis.createClient();
io.sockets.on('connection', function (socket) {
socket.on("subscribe",function(channel){
client.subscribe(channel);
socket.join(channel);
});
client.on("message", function(channel, message){
socket.broadcast.to(channel).emit('message', message);
});
});
When I open the client page in two separate browsers, its subscribing to the two channels correctly and message published to those Redis channels are shown at client side. But if I refresh the page, the number of messages which I get is double and if I refresh again, it adds up. I guess the listeners getting added-up on each refresh.
I have coded the Redis listener inside the socket.io connection listener because I want to emit the message to the socket.This may be cause of the problem am facing. Dono how else to do it as I need socket instance to send message to client side. Please help on this.
as you already told: remove the listener on disconnect.
Have a look at how-to-remove-redis-on-message-listeners and socket-io-handling-disconnect-event for further reading.
untested sample
var client = redis.createClient();
io.sockets.on('connection', function (socket) {
var broadcast = function(channel, message){
socket.broadcast.to(channel).emit('message', message);
}
socket.on("subscribe",function(channel){
client.subscribe(channel);
socket.join(channel);
});
socket.on('disconnect', function() {
client.unsubscribe(channel);
client.removeListener(broadcast)
})
client.on("message", broadcast);
});