io.to(socket.id).emit() not working on cross domain - node.js

how to emit the event with using particular_room [io.to(socket.id).emit('sendData') ]at cross domain
I've tried this,
server side
io.emit('sendData', data);
clientside
var socket = io('https://localhost:3000/', { transports: ['websocket'] });
socket.on('sendData', function (data) {
console.log(data);
})
above syntax are perfectly working on cross domain
but I want to emit with particular room at cross domain
io.to(socket.id).emit('sendData', data)
io.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid
Reference link -> Cross-domain connection in Socket.IO
Kindly help to solve this!

I Understood your code, you just emit the initial connection on the socket.io server
io.on("connection", function(socket){
socket.emit('sendsocketid', data);
})
Cross-domain clientside
var socket = io('https://localhost:3000/', { transports: ['websocket'] });
var obj= [];
socket.on('sendsocketid', function (data) {
console.log(data);
// Now You Can Customize the or add the client Socket .id
var NewSocketid = {
id: socket.id
}
Obj.push(data, NewSocketid)
socket.emit("emitnewSocketId", Obj)
})
socket.on("emitnewSocketId", function(data){
consoleo.log(Obj[1].NewSocketid)
//Now You can emit the new socket id
io.to(Obj[1].NewSocketid).emit('sendData', data)
})

Related

Is it possible to connect to socket.io with get or post request?

I am new in socket.io. I wanted to develop an small application using it. I know the basic of socket.io. I have followed this and this documentation.
I am also able to make this simple connection. Code :
Client:
<script src="/socket.io/socket.io.js"></script>
<script>
console.log(location.protocol+'//'+location.host);
var socket = io.connect(location.protocol+'//'+location.host), socketwithApi = io.connect(location.protocol+'//'+location.host + '/apikey/');
</script>
<script type="text/javascript">
var i=0;
$(document).on('click','#socket-emit-btn', function(){
let message = location.href;
socket.emit("test",message);
});
socket.on("testlistened",function(data){
i ++;
console.log(i);
console.log(data);
if(data){
$("#console-div").html(data);
}else{
$("#console-div").html("{empty}");
}
});
socketwithApi.on('apikey',function(data){
console.log(data);
});
</script>
Server:
//consider everything needed is defined
var apikey = io
.of('/apikey/')
.on('connection', function (socket) {
socket.emit('apikey', { news: 'item' });
});
io.on('connection', function (socket) {
let clientID = socket.id
let clientIP = socket.handshake.address
if (client) client.socket = socket
console.log('User-Client Connected!: IP: ' + clientIP)
socket.on("test",function(data){
console.log("listened");
let ParsedData = url.parse(data);
let responseData = {
UrlScheme:ParsedData,
socketID: clientID,
api_key: ParsedData.pathname
}
console.log(responseData);
console.log(`${TRANSACTIONGETRECEIPT}_RESPONSE`)
socket
.binary(true)
.emit('testlistened', JSON.stringify(responseData))
});
socket.on('disconnect', function (data) {
console.log(clientID + ' has disconnected')
})
})
Everything is working fine, i am able to emit and listen both from the server side and client side. But I did not find the documentation which would tell if it is possible to send http get or post request from the browser or postman to socket.io . Is it only possible to send request from a page where socket client is present or can we also send request like
http://localhost:8099/api-hastgraph-key/socket.io/?EIO=3&transport=websocket&sid=w0kDs4oGI7SVwB3YAAAC
or http://localhost:8099/socket.io/api-hastgraph-key?EIO=3&transport=websocket&sid=w0kDs4oGI7SVwB3YAAAC
from browser and connect to socket.
Thank you. Any kind of help are highly appreciated.

Node.js - Socket.io-client does not emit data

I'm trying to build a simple socket.io-client using nodejs, but I'm facing a trouble...
I'm connecting with the socket.io (server), but I can't emit any data. Follow bellow my simple code:
Client Side:
var socketIO = require('socket.io-client')('http://serverdns:3000');
socketIO.on("dashboard", (data) => {
console.log(data);
});
socketIO.on('connect', function(){
console.log("Connected with the translator service.");
socketIO.emit('dashboard', 'teste');
});
socketIO.on('disconnect', function(){
console.log("Disconnected from the translator service");
});
socketIO.on('error', function(err){
console.log(err);
});
Socket.io version: 2.1.1 (I've tried to use old versions but the same problem happens).
The connect event works, the log "Connected with the translator service." is generated, but emit does not work.
Server side:
var server = require('http').createServer();
var ioServer = require('socket.io')(server, { pingInterval: 2000, pingTimeout: 60000, cookie: false });
class SocketServer {
constructor() {
var self = this;
ioServer.on('connection', function (client) {
console.log('[SOCKETIO] AVAILABLE');
client.on('main', self.main);
client.on('disconnect', self.disconnect);
});
server.listen(3000);
}
getSocket(){
return ioServer;
}
main(data) {
console.log(data);
}
disconnect() {
console.log("[SOCKETIO] DISCONNECTED");
}
}
module.exports = new SocketServer();
Anyone can help me?
Are there anything I'm not seeing?
Thanks a lot.
Right now you are emitting to the event dashboard from client. But on the server side you have no code that is handling that event. You are currently logging the event main which does not match with what you're emitting. Try client.on('dashboard', self.dashboard). Make your own dashboard function.

Socket.io, Node, Corodva, I don't recive message in client receptor

I have a problem when I try send message from a client emisor with "emit" and I try catch the message with "on" in a client receptor.
I don't know what is the problem, my code is this:
Emisor Client:
socket.emit("callDriver", data);
Receptor Client:
socket.on("sendToDriver", function(data){
console.log(data);
})
Server:
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('callDriver', function(data){
console.log(data);
socket.emit('sendToDriver', data);
})
})
Thanks community
Guys I resolved the problem, it's strange in the official documentation of Socket.io they say that when you send data in a .emit you should send this with "socket.emit()" (server side) but I try change socket for io and with this mode work it.
In conclusion:
// I changed this:
io.on('connection', function(socket){
socket.on('callDriver', function(data){
console.log(data);
socket.emit('sendToDriver', data);
})
})
// for this:
io.on('connection', function(socket){
socket.on('callDriver', function(data){
console.log(data);
io.emit('sendToDriver', data);
})
})
Thanks guys!
Here is a simple rooms solution for you. The init() part is very low-tech/simple but you did not say how you intend to populate the socket server with the client userId/session-data when you connect to the server for the first time.
//Client
socket.on('connect',()=>{
socket.on('init',()=>{
socket.emit('init', 'userid')
})
})
socket.on("sendToDriver", function(message){
console.log(message);
})
sendMessage(message){
let data = {userId: "userId", message: message}
socket.emit("callDriver", data);
}
//Server
var io = require('socket.io')(server);
//Triggered by each client separately.
io.on('connection', function(socket){
socket.on('init', (driverId)=>{
//When your web socket starts for the first time, each user creates their own room with their main userId that is used in your mobile app.
//Your setup is so basic, that the server('connection') -> server.emit('init') -> client.on('init') -> client.emit('init') flow is the most sane example for now.
//However this init() setup is primitive -- you need an authentication flow and to pass up the userId/session data with a socket.io 'middleware' function or the 'socket.io-auth' library (recommended)
socket.join(driverId)
})
socket.emit('init')
//Data sent to callDriver will contain the userId of the desired receipient. Since this user is already waiting in that room for us, we join it,
//send the message, and then leave immediately.
socket.on('callDriver', function(data){
socket.join(data.driverIdToCall)
socket.to(data.driverIdToCall).emit('sendToDriver', data.message);
socket.leave(data.driverIdToCall)
})
})

Socket.io communicating from server to client not happening

i am trying to do a very simple real time notification with socket.io. for some reason i can't receive data or fire the event from server to client but from client to server yes. let me show my code:
Client Side
ngOnInit() {
this.socket.on('connect', function (res: any) {
console.log('Socket.io is connected on client side!'); // it shows on client console
});
this.socket.on('alarmsreceived', function (res: any) {
console.log(res + ' i am here now'); // is not firing
});
}
// this method fires from a click button
objectStatus = () => {
this.socket.emit('alarmsystem', 'i am client going to server');
}
Server
var io = require('socket.io').listen(server);
var connections = [];
io.of('/api/v1/monitoring').on('connect', function(socket){
connections.push(socket);
console.log('Connected %s sockets', connections.length); // i see connection on cmd
socket.on('disconnect', function() {
connections.splice(connections.indexOf(socket), 1);
console.log('Connected %s sockets', connections.length);
});
socket.on('alarmsystem', function(res) {
console.log(res); // this shows me the message from client
io.sockets.emit('alarmsreceived', 'I am server heading to client');
});
})
it seems pretty straight forward, but not firing the client event. Can someone help me what i am doing wrong here? Thanks in advance

Send a message from client to server on connection node.js

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)
}
}

Resources