Here is the code :
Client
var server = "localhost";
var socket = io('http://' + serve + ':4005');
socket.on('connect',function(){
socket.emit('send', {type:"<?php echo $datatype?>"}); //{type:"3,2"}
});
Here is the code for my node js server:
Server
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
client.on('send',function(data){
var datafinal = [];
setInterval(function () {
var usertype = data.type;
var types = usertype.split(',');
for (var i = 0; i < types.length; i++){
datafinal.push(apifinaldata.filter((inbound) => inbound.usertype == types[i] && inbound.active == 1 ));
}
var final = datafinal.reduce(function(a, b) {
return a.concat(b);
}, []);
datafinal = [];
io.emit('finaldata', final); io.emit('callwaiting', callsdatafinal);
}, 1000);
})
});
server.listen(4005);
When I start the server, it receives a request from client A with the type of data it want's (eg {type : "3,2" }
. So the server emits only that specific data to client. But when a different client say B asks the server to send data of {type : "1"}
, in this case the server emits the correct data to client A and B each but the clients don't receive the data continously. The server keeps emitting continously but sometimes it sometimes emits to A and sometimes to B. I want the server to continously emit the requested data to each of the connected clients.
Also if I change io.emit('finaldata', final); io.emit('callwaiting', callsdatafinal); to client.emit('finaldata', final); client.emit('callwaiting', callsdatafinal); it doesn't emit any data to any client.
So I want a solution such that the server emits continuously to each client only the specific data requested by each client
How can I do this?
For this you have to keep track of both the clients A and B then send data to specific client only, Below is sample code.
Here clientA and clientB are two clients connected, You can send data to any client based on conditions or program logic.