Namespacing in socket.io when sending to a particular socket - javascript

When i namespace my app, i run into a problem i want to send data to a particular socket, here's the abbreviated version of the code I'm using:
var io = require('socket.io').listen(config.web.port);
var chat = io.of('space').on('connection', function (socket) {
// This works:
// Input: xhr-polling received data packet 5::/space:{"name":"test"}
// Output: xhr-polling writing 5::/space:{"name":"test","args":[{"msg":"test"}]}
socket.on('test', function(){
socket.emit('test',{msg: "test"});
});
// This fails:
// Input: xhr-polling received data packet 5::/space:{"name":"test2"}
// Output: xhr-polling writing 5:::{"name":"test2","args":[{"msg":"test2"}]}
socket.on('test2',function(){
io.sockets.socket(socket.id).emit('test2',{msg: "test2"});
});
}
As you can see, the second one lacks the namespace part from the output. In the real app I'm picking the socket id from a client manager so I'm using socket.id in this piece of code instead of client.getSocketId(), but the idea is the same as I'm just echoing to the origin client here.
How do i make the second method to use the correct namespace when outputting to the client?

After checking out the source for SocketNamespace, it appears the syntax is io.of('space').socket(id).emit(....
[Edit per Fuu's comment]
To find this, I checked the Socket.IO GitHub repository and looked for a file that would have to do with namespaces--namespace.js seemed to fit the bill. The file wasn't very long, so I scanned it looking for methods on SocketNamespace's prototype that looked like it might do what we wanted.
Since you call io.sockets.socket to find a socket on the global namespace, SocketNamespace.prototype.socket stuck out to me as being promising. Furthermore, it takes a parameter called sid, and the body of the method appears to be fetching a socket from a hash of sockets by this ID. A Socket is what we want (it holds the emit method), so my presumption was that this is the method to use in this case.

Related

matrix-js-sdk setup and configuration

I am having some issues trying to connect to a matrix server using the matrix-js-sdk in a react app.
I have provided a simple code example below, and made sure that credentials are valid (login works) and that the environment variable containing the URL for the matrix client is set. I have signed into element in a browser and created two rooms for testing purposes, and was expecting these two rooms would be returned from matrixClient.getRooms(). However, this simply returns an empty array. With some further testing it seems like the asynchronous functions provided for fetching room, member and group ID's only, works as expected.
According to https://matrix.org/docs/guides/usage-of-the-matrix-js-sd these should be valid steps for setting up the matrix-js-sdk, however the sync is never executed either.
const matrixClient = sdk.createClient(
process.env.REACT_APP_MATRIX_CLIENT_URL!
);
await matrixClient.long("m.login.password", credentials);
matrixClient.once('sync', () => {
debugger; // Never hit
}
for (const room of matrixClient.getRooms()) {
debugger; // Never hit
}
I did manage to use the roomId's returned from await matrixClient.roomInitialSync(roomId, limit, callback), however this lead me to another issue where I can't figure out how to decrypt messages, as the events containing the messages sent in the room seems to be of type 'm.room.encrypted' instead of 'm.room.message'.
Does anyone have any good examples of working implementations for the matrix-js-sdk, or any other good resources for properly understanding how to put this all together? I need to be able to load rooms, persons, messages etc. and display these respectively in a ReactJS application.
It turns out I simply forgot to run startClient on the matrix client, resulting in it not fetching any data.

Node.js, Socket.io emit not working

I am making a website in Socket.io. But emit method not working in my code. I can't see any errors in my code. Here is my server code.
var io = require("socket.io").listen(server);
//Some external codes for running server in Node.js
io.on("connection", function(socket) {
//This line is working.
console.log("Socket connected.");
io.on("requestNewMap", function(data) {
//Create new map object in here.
io.emit("responseNewMap", { mapData: map });
});
});
And this is my client side javascript code.
var socket = io();
socket.on("responseNewMap", function(data) {
var map = data.mapData;
//Draw map in canvas's context.
});
//setInterval runs this method every 2 seconds.
function requestNewMap() {
socket.emit("requestNewMap");
}
This part could be wrong:
io.on("requestNewMap", function(data) {
//Create new map object in here.
io.emit("responseNewMap", { mapData: map });
});
I would use socket there as in:
socket.on("requestNewMap", function(data) {
//Create new map object in here.
socket.emit("responseNewMap", { mapData: map });
});
I think io.emit should work fine, it would just send the response to every connected client, but io.on('requestNewMap',...) won't work since requestNewMap is not an io standard event.
change this
io.on("requestNewMap", function(data) {
//Create new map object in here.
io.emit("responseNewMap", { mapData: map });
});
into this
socket.on("requestNewMap", function(data) {
//Create new map object in here.
socket.emit("responseNewMap", { mapData: map });
});
you are adding an event listener to the server object not the client socket.
I'm not certain, but I believe your problem is that your function on the client side is written like you are expective 'requestNewMap' to be passing along data.
Instead of:
io.on("requestNewMap", function(data){
Try:
io.on("requestNewMap", function(){
OR pass an empty object or some other kind of junk data along with the emit from client side like this:
function requestNewMap() {
socket.emit("requestNewMap", {});
}
function requestNewMap() {
socket.emit("requestNewMap", undefined);
}
function requestNewMap() {
socket.emit("requestNewMap", -1);
}
Hopefully this is helpful and correct!
Edit: This turned out to not be the answer to your question, but still something worth considering. If you're not passing data along you should avoid writing the event handler as if it expects data.
This works fine only you want to send the "responseNewMap" event back to the sender only.
socket.on("requestNewMap", function(data) {
//Create new map object in here.
socket.emit("responseNewMap", { mapData: map });
});
Implement this if you want to send the event back to all connected users
socket.on("requestNewMap", function(data) {
//Create new map object in here.
io.emit("responseNewMap", { mapData: map });
});
If you use a namespace like this:
io.of('/api/v1/chat').on('connection', function (socket) {
//Your code here
});
Then include a namespace like this:
io.of('/api/v1/chat').emit("responseNewMap", { mapData: map })
I'm going to respond to this as a note to myself and others on the whole socket.emit is not working situation...
So I had issues with socket.emit not firing to the socket that made the initial request out. The issue was not an issue, more so the way client works. I was indeed emitting to the originator only when using socket.emit (which is what I wanted, only the requested got the response) but the issue was that I had more than one socket on in my app.
I use ES6 and imports (import 'path to socket io client js') which is also an issue without webpack unless you do it like that, as i have my own web component framework.
I had 3 components all creating a socket from io(), expecting them to use the same manager and they where not.
socket.io will not use the same manager over many mjs files all creating this.socket = io(); they are indeed all new isolated sockets! So take this in mind, you may be returning the message to the socket that sent the request out but if your listener is in another component than thats got a different socket.id and in essence is a whole new socket connection.
There is an option to pass in to io called forceNew which is true by default so it appears, but changing this still gave me the same issues albeit the ID's where all now the same, however I still could not seem to get a listening component to get responses from an action in an action component even though both had the same ID now. A bug maybe or something else, not sure.
So short answer is importing via ES6 without webpack needs to be just import 'fsdfsd.js'; and to save issues, only generate one socket and share between components, which you may want to do anyway as sockets are not cheap and you dont want to use many for one app!
This is my first time playing with sockets, they are great, but use sparingly and do not hold them open if you want authenticated people only, drop if not authed!
Hope this helps someone, had me lost for a day or too.
In my case, setting homepage to "." in package.json fixed the problem.

Socket.IO: Remove specific socket_id from room?

I have a specific socket_id that I want to remove from a room in socket.io. Is there an easy way to do this? The only way I can find is to disconnect by the socket itself.
From the client, you send your own message to the server and ask the server to remove it from the room. The server can then use socket.leave("someRoom") to remove that socket from a given room. Clients cannot join or leave rooms themselves. Joining and leaving to/from rooms has to be done by the server (because the whole notion of chat rooms only really exists on the server).
Documentation here.
For socket.io version 4.0.0 upwards (Mine is version 4.4.0):
Step #1) You have to get an array of the sockets connected to that socket.id as shown in the code below.
//You can replace the userStatus.socketId to your own socket id, that was what I
//used in my own case
const userSockets = await io.of("/chat").in(userStatus.socketId).fetchSockets();
Step #2) After getting all the socket IDs, you will be given an array containing the individual socket (I got to know this by logging the results from the async and await fetchSockets() method that the io library on the server offered). Then use the .find() method to return the single socket object matching that same socket id again as shown below.
const userSocket = userSockets.find(socket => socket.id.toString() === userStatus.socketId);
// Replace userStatus.socketId with your own socket ID
Step #3) Remove the socket by leaving the group using the .leave() method of the socket.io library as shown below.
userSocket.leave(groupId);
// groupId can be replaced with the name of your room
Final Notes: I hope this helps someone in the future because this was what I used and it worked for me.

Strange issue with socket.on method

I am facing a strange issue with calling socket.on methods from the Javascript client. Consider below code:
for(var i=0;i<2;i++) {
var socket = io.connect('http://localhost:5000/');
socket.emit('getLoad');
socket.on('cpuUsage',function(data) {
document.write(data);
});
}
Here basically I am calling a cpuUsage event which is emitted by socket server, but for each iteration I am getting the same value. This is the output:
0.03549148310035006
0.03549148310035006
0.03549148310035006
0.03549148310035006
Edit: Server side code, basically I am using node-usage library to calculate CPU usage:
socket.on('getLoad', function (data) {
usage.lookup(pid, function(err, result) {
cpuUsage = result.cpu;
memUsage = result.memory;
console.log("Cpu Usage1: " + cpuUsage);
console.log("Cpu Usage2: " + memUsage);
/*socket.emit('cpuUsage',result.cpu);
socket.emit('memUsage',result.memory);*/
socket.emit('cpuUsage',cpuUsage);
socket.emit('memUsage',memUsage);
});
});
Where as in the server side, I am getting different values for each emit and socket.on. I am very much feeling strange why this is happening. I tried setting data = null after each socket.on call, but still it prints the same value. I don't know what phrase to search, so I posted. Can anyone please guide me?
Please note: I am basically Java developer and have a less experience in Javascript side.
You are making the assumption that when you use .emit(), a subsequent .on() will wait for a reply, but that's not how socket.io works.
Your code basically does this:
it emits two getLoad messages directly after each other (which is probably why the returning value is the same);
it installs two handlers for a returning cpuUsage message being sent by the server;
This also means that each time you run your loop, you're installing more and more handlers for the same message.
Now I'm not sure what exactly it is you want. If you want to periodically request the CPU load, use setInterval or setTimeout. If you want to send a message to the server and want to 'wait' for a response, you may want to use acknowledgement functions (not very well documented, but see this blog post).
But you should assume that for each type of message, you should only call socket.on('MESSAGETYPE', ) once during the runtime of your code.
EDIT: here's an example client-side setup for a periodic poll of the data:
var socket = io.connect(...);
socket.on('connect', function() {
// Handle the server response:
socket.on('cpuUsage', function(data) {
document.write(data);
});
// Start an interval to query the server for the load every 30 seconds:
setInterval(function() {
socket.emit('getLoad');
}, 30 * 1000); // milliseconds
});
Use this line instead:
var socket = io.connect('iptoserver', {'force new connection': true});
Replace iptoserver with the actual ip to the server of course, in this case localhost.
Edit.
That is, if you want to create multiple clients.
Else you have to place your initiation of the socket variable before the for loop.
I suspected the call returns average CPU usage at the time of startup, which seems to be the case here. Checking the node-usage documentation page (average-cpu-usage-vs-current-cpu-usage) I found:
By default CPU Percentage provided is an average from the starting
time of the process. It does not correctly reflect the current CPU
usage. (this is also a problem with linux ps utility)
But If you call usage.lookup() continuously for a given pid, you can
turn on keepHistory flag and you'll get the CPU usage since last time
you track the usage. This reflects the current CPU usage.
Also given the example how to use it.
var pid = process.pid;
var options = { keepHistory: true }
usage.lookup(pid, options, function(err, result) {
});

Node.JS Socket.IO sending packets to specific connection IDs

I have been searching for this particular problem for the past week, and since I couldn't find any information on the subject(that wasnt outdated), I just decided to work on other things. But now I am at the point where I need to be able to send data(that I constructed) to specific clients using their ID who are connected to my server using node.js and socket.io. I already store the ID in an object for each new connection. What I need to know is a way to just send it to a connection ID I choose.
Something like: function send(data, client.id) {};
I am using an http server, not TCP.
Is this possible?
edit:
server = http_socket.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(respcont);
client_ip_address = req.header('x-forwarded-for');
});
socket = io.listen(1337); // listen
//=============================================
// Socket event loop
//=============================================
socket.on ('connection', function (client_connect) {
var client_info = new client_connection_info(); // this just holds information
client_info.addNode(client_connect.id, client_connect.remoteAddress, 1); // 1 = trying to connet
var a = client_info.getNode(client_connect.id,null,null).socket_id; // an object holding the information. this function just gets the socket_id
client_connect.socket(a).emit('message', 'hi');
client_connect.on('message', function (data) {
});
client_connect.on ('disconnect', function () {
);
});
solution: I figured it out by just experimenting... What you have todo is make sure you store the SOCKET, not the socket.id (like i was doing) and use that instead.
client_info.addNode(client_connect.id, client_connect.remoteAddress, client_connect, 1)
var a = client_info.getNode(client_connect.id,null,null,null).socket;
a.emit('message', 'hi');
If you need to do this, the easiest thing to do is to build and maintain a global associative array that maps ids to connections: you can then look up the appropriate connection whenever you need and just use the regular send functions. You'll need some logic to remove connections from the array, but that shouldn't be too painful.
Yes, it is possible.
io.sockets.socket(id).emit('message', 'data');
Your solution has one major drawback: scaling. What will you do when your app needs more the one machine? Using internal IDs also could be difficult. I advice using external IDs (like usernames).
Similarly to this post I advice using rooms (together with Redis to allow scaling). Add private room for every new socket (basing on user's name for example). The code may look like this:
socket.join('priv/' + name);
io.sockets.in('priv/' + name).emit('message', { msg: 'hello world!' });
This solution allows multiple machines to emit events to any user. Also it is quite simple and elegant in my opinion.

Categories

Resources