socket.io disconnect after emitting to specific client NODE javascript - javascript

Hello I am currently working on some kind of "Chat"-system.
Server: NodeJs with express - https
Communication: Socket.io#1.0
client:
var socket = io.connect();
socket.emit('HELLO', {user:'someuserid'});
socket.on('WELCOME', function(data){
socket.emit('REGISTER', {});
});
socket.on('SIGNED', function(data){
console.log(data.user);
socket.emit('GO', {});
});
socket.on('message', function(data){
console.log(data.somedata);
});
server:
io.sockets.on('connection', function(socket){
socket.on('HELLO', function(data){
socket.user = data.user;
socket.emit('WELCOME', socket.user);
});
socket.on('REGISTER', function(data){
console.log('room: '+socket.user);
socket.join(socket.user);
socket.emit('SIGNED', socket.user);
console.log('SIGNED IN: '+socket.user);
});
socket.on('GO', function(data){
//some logic happens where a list of users gets loaded
//which is identical to the socket.user and its room
//... loop
io.in(partners[i].user).emit('message', { somedata: 'asd' });
}
socket.on('disconnect' ..... blaaa blaa)
So, basicly what I tried to do here is create a workaround to sending a message to a specific user by sending a message to a specific room.
this:
io.in(partners[i].user).emit('message', { somedata: 'asd' });
and this:
partners[i].socket.emit('message', { somedata: 'asd' });
result in the same:
room: 540246a3e4b0a64a28e1ec59
SIGNED IN: 540246a3e4b0a64a28e1ec59
room: 540504ba0b526b274398480e
SIGNED IN: 540504ba0b526b274398480e
to: 540246a3e4b0a64a28e1ec59
disconnected:540246a3e4b0a64a28e1ec59
the user registers, gets connected and wants to emit a message to specific chatpartners in the array partners[i].
once the emit is fired the user, the message is supposed to be emitted to disconnects...
what am I doing wrong?
(the script is obviously not complete.. i pasted the most important parts)
Thanks for your help.

I think I have found the solution:
sometimes using google is more effort than debugging by yourself.
After scrolling through the debug log in firefox I found out that this problem actually had to do with the code inside my socket 'message' handler. A snippet that might help others to find errors with their sockets:
socket.on('error', function (err) {
if (err.description) throw err.description;
else throw err; // Or whatever you want to do
});
I think this is an issue in socket.io
although it was my wrong code - the socket.io errorhandler should have passed that through.
Have fun

Related

Socket.io—about socket disconnect

I have this scenario with socket.io:
I want to receive the data from a sever and Forward the data to webclient.But when I receive a lot of data and close the page, it console
DISCONNECTED FROM CLIENT
DISCONNECTED FROM CLIENT
DISCONNECTED FROM CLIENT
DISCONNECTED FROM CLIENT
DISCONNECTED FROM CLIENT
DISCONNECTED FROM CLIENT
DISCONNECTED FROM CLIENT
...(a lot)
Here is the code:
server:
var express=require('express');
var app=express();
var net=require('net');
var http=require('http').createServer(app);
var io=require('socket.io')(http);
var net=require('net');
var nodeServer = new net.Socket();
var aSocket=null;
io.on('connection', function (socketIO) {
aSocket=socketIO;
};
nodeServer.on('data', function(data) {
if(aSocket!=null){
aSocket.emit('pushToWebClient',useData);
aSocket.on('disconnect', function () {
console.log('DISCONNECTED FROM CLIENT');
});
}
client:
socket.on('pushToWebClient', function (useData) {
});
I find
aSocket.on('disconnect', function () {
console.log('DISCONNECTED FROM CLIENT');
});
console a lot of'DISCONNECTED FROM CLIENT' but actually it should console just once in the code.
I had even console.log(aSocket.id),it console just only one.
I don't know why it is console so many times.
I haved used setMaxListeners(10) to try to avoid it .
Will it lead to a memory leak?
It appears that you are registering multiple event listeners for the same disconnect event. In this code:
nodeServer.on('data', function(data) {
if(aSocket!=null){
aSocket.emit('pushToWebClient',useData);
aSocket.on('disconnect', function () {
console.log('DISCONNECTED FROM CLIENT');
});
}
You appear to be registering a new disconnect event listener every time you get a data message. So, if you have multiple listeners, then each one will get called when the socket disconnects and the result is that you will log the same message multiple times all for the same socket.
You can verify this is what is happening by moving your disconnect handler into the connection handler so it is only ever attached just once for each socket.
In addition putting asocket into a global or module-level variable means that your server code would only ever work with one single client at a time. It is not clear exactly what you are trying to do when you get data on the nodeserver connection - whether you're trying to send that data to only one specific client or to all connected clients.
I try to delete the code:
aSocket.on('disconnect', function () {
console.log('DISCONNECTED FROM CLIENT');
});
or moving it out of nodeServer handler,
it turn into normal and never suggest me to setMaxlisener.
I think maybe it is incorrect put one API into a API
And the envent maybe not release the socket,so it console multiple times .
EDIT: I'm moving this to the top because I saw that someone already provided my solution but you were having a problem managing the data sent to the client. Your aSocket variable will be overwritten by every new client that connects to your app. If you want to send data to a specific client using your server nodeServer, you should create a global variable (an array) that keeps track of all of your client socket connections. So instead of using one global variable aSocket do the following:
var net=require('net');
var nodeServer = new net.Socket();
var clients = [];
io.on('connection', function (socketIO) {
clients.push(socketIO);
var clientNum = clients.length-1;
aSocket.on('disconnect', function () {
clients.splice(clientNum, 1);
console.log('DISCONNECTED FROM CLIENT: '+socketIO.id);
});
};
nodeServer.on('data', function(data) {
//have your data object contain an identifier for the client that caused the handler to fire
//for the sake of the answer I just use data.id
var clientID = data.id;
if(clients[clientID]!=null){
clients[clientID].emit('pushToWebClient', useData);
}
}
Let me know how it goes! My original answer is below:
Try moving
aSocket.on('disconnect', function () {
console.log('DISCONNECTED FROM CLIENT');
});
out of your nodeServer.on('data', ...) event listener into the io.on('connection', ...) event listener like so:
io.on('connection', function (socketIO) {
aSocket=socketIO;
aSocket.on('disconnect', function () {
console.log('DISCONNECTED FROM CLIENT');
});
};
socket.io is designed to keep polling for the presence of the server/client. If either the server or the client are disconnected, the remaining 'side' continues to receive polling requests and, consequently, will continuously print an error.
You can see this effect on the client side in your browser when you disconnect your server and leave the client page open. If you look at the browser's error/console log what you should see is a continuous stream of net::ERR_CONNECTION_REFUSED errors. By placing the disconnect event handler in the .on('data', ...) handler for your server, you are seeing the converse of this situation.
net:ERR_CONNECTION_REFUSED example
This is basic code for socket.io
The following example attaches socket.io to a plain Node.JS HTTP
server listening on port 3000.
var server = require('http').createServer();
var io = require('socket.io')(server);
io.on('connection', function(client){
client.on('event', function(data){});
client.on('disconnect', function(){});
});
server.listen(3000);
I think, you should try.

How to handle multiple, dynamically created listeners to a single ChildProcess in NodeJS?

I have a child process worker, that receives some data and sends back results to dynamically attached listener.
Simplified code:
//app.js
var worker = childProcess.fork('./app_modules/workers/worker1.js');
worker.setMaxListeners(0);
require('./app_modules/sockets-user/foobar.js')(io, worker);
//foobar.js
io.sockets.on('connection', function (socket) {
socket.on('trigger', function (data) {
worker.send(data);
worker.once('message', function(responseData) {
//here I get a response from worker
socket.emit('response', responseData);
});
});
});
It was working great until I discovered that If socket.on('trigger' is triggered at the very exact moment by different users every listener would receive the same message.
I could change worker.once to worker.on but its not a fix, because I would have to filter incoming data and then probably find a way to clear dynamically added listeners. What did I do wrong here?
Probably one of the easiest solutions would be to pass some user-specific data (e.g. remote IP address and port or some other unique identifier) to the worker than merely gets passed right back to the parent in the response. This way you can match up the response with the correct socket.
This means that you would only have one message listener (added outside of the socket.io connection handler). You would then look up the socket based on the information passed in the response, and send whatever data back to that client. For example:
//foobar.js
worker.on('message', function(responseData) {
// assuming worker returns `{id: ..., data: ...}`
var socket = io.sockets.sockets[responseData.id];
if (socket)
socket.emit('response', responseData.data);
});
io.sockets.on('connection', function (socket) {
socket.on('trigger', function (data) {
worker.send({ id: socket.id, data: data });
});
});

How do I subscribe to a model instance in Sails.JS?

I am attempting to use the subscribe function described here. However, when editing /assets/js/app.js, I am getting this error:
Uncaught ReferenceError: Room is not defined
So, I am not entirely sure why, but it cannot find my model. Here is my code:
Room.subscribe(req, [{id: "5278861ab9a0d2cd0e000001"}], function (response) {
console.log('subscribed?');
console.log(response);
});
and here is is in the context of app.js
(function (io) {
// as soon as this file is loaded, connect automatically,
var socket = io.connect();
if (typeof console !== 'undefined') {
log('Connecting to Sails.js...');
}
socket.on('connect', function socketConnected() {
// Listen for Comet messages from Sails
socket.on('message', function messageReceived(message) {
///////////////////////////////////////////////////////////
// Replace the following with your own custom logic
// to run when a new message arrives from the Sails.js
// server.
///////////////////////////////////////////////////////////
log('New comet message received :: ', message);
//////////////////////////////////////////////////////
});
///////////////////////////////////////////////////////////
// Here's where you'll want to add any custom logic for
// when the browser establishes its socket connection to
// the Sails.js server.
///////////////////////////////////////////////////////////
log(
'Socket is now connected and globally accessible as `socket`.\n' +
'e.g. to send a GET request to Sails, try \n' +
'`socket.get("/", function (response) ' +
'{ console.log(response); })`'
);
///////////////////////////////////////////////////////////
// This is the part I added:
Room.subscribe(req, [{id: "5278861ab9a0d2cd0e000001"}], function (response) {
console.log('subscribed?');
console.log(response);
});
//
});
// Expose connected `socket` instance globally so that it's easy
// to experiment with from the browser console while prototyping.
window.socket = socket;
// Simple log function to keep the example simple
function log () {
if (typeof console !== 'undefined') {
console.log.apply(console, arguments);
}
}
})(
Am I going about this the right way? should I be storing this directly in app.js?
To subscribe to a model instance, I use the following Real-Time Model Event pattern, some of which resides on the client and some on the server. Keep in mind the client can’t just subscribe itself- you have to send a request to the server letting it know that you’d like to be subscribed-- this is the only way to do it securely. (e.g. you might want to publish notifications with sensitive information-- you want to make sure a connected socket has permission to see that information before subscribing them to it.)
I’m going to use an example of an app with a User model. Let’s say I want to notify folks when existing users login.
Client-Side (Part I)
On the client-side, for simplicity, I’m going to use the existing app.js file in the /assets/js folder (or /assets/linker/js folder if you used the --linker switch when you built the app.)
To send my socket request to the server within assets/js/app.js, I’m going to use the socket.get() method. This method mimics the functionality of an AJAX “get” request (i.e. $.get() ) but uses sockets instead of HTTP. (FYI: You also have access to socket.post(), socket.put(), and socket.delete()).
The code would look something like this:
// Client-side (assets/js/app.js)
// This will run the `welcome()` action in `UserController.js` on the server-side.
//...
socket.on('connect', function socketConnected() {
console.log("This is from the connect: ", this.socket.sessionid);
socket.get(‘/user/welcome’, function gotResponse () {
// we don’t really care about the response
});
//...
Server-Side (Part I)
Over in the welcome() action in UserController.js, now we can actually subscribe this client (socket) to notifications using the User.subcribe() method.
// api/UserController.js
//...
welcome: function (req, res) {
// Get all of the users
User.find().exec(function (err, users) {
// Subscribe the requesting socket (e.g. req.socket) to all users (e.g. users)
User.subscribe(req.socket, users);
});
}
//...
Back on the client-side (Part II)...
I want the socket to ‘listen’ for messages I’m going to send it from the server. To do this I’ll use:
// Client-side (assets/js/app.js)
// This will run the `welcome()` action in `UserController.js` on the backend.
//...
socket.on('connect', function socketConnected() {
console.log("This is from the connect: ", this.socket.sessionid);
socket.on('message', function notificationReceivedFromServer ( message ) {
// e.g. message ===
// {
// data: { name: ‘Roger Rabbit’},
// id: 13,
// verb: ‘update’
// }
});
socket.get(‘/user/welcome’, function gotResponse () {
// we don’t really care about the response
});
// ...
Back on the server-side (Part II)...
Finally, I’ll start sending out messages, server-side, by using: User.publishUpdate(id);
// api/SessionController.js
//...
// User session is created
create: function(req, res, next) {
User.findOneByEmail(req.param('email'), function foundUser(err, user) {
if (err) return next(err);
// Authenticate the user using the existing encrypted password...
// If authenticated log the user in...
// Inform subscribed sockets that this user logged in
User.publishUpdate(user.id, {
loggedIn: true,
id: user.id,
name: user.name,
action: ' has logged in.'
});
});
}
//...
You can also check out Building a Sails Application: Ep21 - Integrating socket.io and sails with custom controller actions using Real Time Model Events for more information.

socket.io/node.js detecting if server is down

Is there something that I can do on the client side to detect that the socket.io websocket is not available? Something along the lines of:
server starts as per usual
clients connect
messages are sent back and forth between server and client(s)
server shuts down (no longer available)
warn the connected clients that the server is not available
I tried to add the 'error' and 'connect_failed' options on the client side but without any luck, those didn't trigger at all. Any ideas from anyone how I can achieve this?
The disconnect event is what you want to listen on.
var socket = io.connect();
socket.on('connect', function () {
alert('Socket is connected.');
});
socket.on('disconnect', function () {
alert('Socket is disconnected.');
});
If you want to be able to detect that the client was not able to connect to the server, then try using connect_error. This works for me with socket.io-1.3.5.js. I found this in https://stackoverflow.com/a/28893421/2262092.
Here's my code snippet:
var socket = io.connect('http://<ip>:<port>', {
reconnection: false
});
socket.on('connect_error', function() {
console.log('Failed to connect to server');
});
hit this bug during my development and noticed my event calls were doubling up every time i reset the server, as my sockets reconnected. Turns out the solution that worked for me, which is not duping connections is this
var socket = io.connect();
socket.on('connect', function () {
console.log('User connected!');
});
socket.on('message', function(message) {
console.log(message);
});
( Found this at https://github.com/socketio/socket.io/issues/430 by KasperTidemann )
Turns out, it was becuase I put the 'message' listener inside the 'connect' function. Seating it outside of the listener, solves this problem.
Cheers to Kasper Tidemann, whereever you are.
Moving on!!
connect_error didn't work for me (using Apache ProxyPass and returns a 503).
If you need to detect an initial failed connection, you can do this.
var socket;
try {
socket = io();
}
catch(e) {
window.location = "nodeServerDown.php";
}
Redirects the user to a custom error page when the server is down.
If you need to handle a disconnect after you've connected once.
You do this:
socket.on('disconnect', function() {
//whatever your disconnect logic is
});

Send message to specific client with socket.io and node.js

I'm working with socket.io and node.js and until now it seems pretty good, but I don't know how to send a message from the server to an specific client, something like this:
client.send(message, receiverSessionId)
But neither the .send() nor the .broadcast() methods seem to supply my need.
What I have found as a possible solution, is that the .broadcast() method accepts as a second parameter an array of SessionIds to which not send the message, so I could pass an array with all the SessionIds connected at that moment to the server, except the one I wish send the message, but I feel there must be a better solution.
Any ideas?
Ivo Wetzel's answer doesn't seem to be valid in Socket.io 0.9 anymore.
In short you must now save the socket.id and use io.sockets.socket(savedSocketId).emit(...) to send messages to it.
This is how I got this working in clustered Node.js server:
First you need to set Redis store as the store so that messages can go cross processes:
var express = require("express");
var redis = require("redis");
var sio = require("socket.io");
var client = redis.createClient()
var app = express.createServer();
var io = sio.listen(app);
io.set("store", new sio.RedisStore);
// In this example we have one master client socket
// that receives messages from others.
io.sockets.on('connection', function(socket) {
// Promote this socket as master
socket.on("I'm the master", function() {
// Save the socket id to Redis so that all processes can access it.
client.set("mastersocket", socket.id, function(err) {
if (err) throw err;
console.log("Master socket is now" + socket.id);
});
});
socket.on("message to master", function(msg) {
// Fetch the socket id from Redis
client.get("mastersocket", function(err, socketId) {
if (err) throw err;
io.sockets.socket(socketId).emit(msg);
});
});
});
I omitted the clustering code here, because it makes this more cluttered, but it's trivial to add. Just add everything to the worker code. More docs here http://nodejs.org/api/cluster.html
each socket joins a room with a socket id for a name, so you can just
io.to('socket#id').emit('hey')
docs: http://socket.io/docs/rooms-and-namespaces/#default-room
The simplest, most elegant way
verified working with socket.io v3.1.1
It's as easy as:
client.emit("your message");
And that's it. Ok, but how does it work?
Minimal working example
Here's an example of a simple client-server interaction where each client regularly receives a message containing a sequence number. There is a unique sequence for each client and that's where the "I need to send a message to a particular client" comes into play.
Server
server.js
const
{Server} = require("socket.io"),
server = new Server(8000);
let
sequenceNumberByClient = new Map();
// event fired every time a new client connects:
server.on("connection", (socket) => {
console.info(`Client connected [id=${socket.id}]`);
// initialize this client's sequence number
sequenceNumberByClient.set(socket, 1);
// when socket disconnects, remove it from the list:
socket.on("disconnect", () => {
sequenceNumberByClient.delete(socket);
console.info(`Client gone [id=${socket.id}]`);
});
});
// sends each client its current sequence number
setInterval(() => {
for (const [client, sequenceNumber] of sequenceNumberByClient.entries()) {
client.emit("seq-num", sequenceNumber);
sequenceNumberByClient.set(client, sequenceNumber + 1);
}
}, 1000);
The server starts listening on port 8000 for incoming connections. As soon as a new connection is established, that client is added to a map that keeps track of its sequence number. The server also listens for the disconnect event to remove the client from the map when it leaves.
Each and every second, a timer is fired. When it does, the server walks through the map and sends a message to every client with their current sequence number, incrementing it right after. That's all that is to it. Easy peasy.
Client
The client part is even simpler. It just connects to the server and listens for the seq-num message, printing it to the console every time it arrives.
client.js
const
io = require("socket.io-client"),
ioClient = io.connect("http://localhost:8000");
ioClient.on("seq-num", (msg) => console.info(msg));
Running the example
Install the required libraries:
npm install socket.io#3.1.1 socket.io-client#3.1.1
Run the server:
node server
Open other terminal windows and spawn as many clients as you want by running:
node client
I have also prepared a gist with the full code here.
Well you have to grab the client for that (surprise), you can either go the simple way:
var io = io.listen(server);
io.clients[sessionID].send()
Which may break, I doubt it, but it's always a possibility that io.clients might get changed, so use the above with caution
Or you keep track of the clients yourself, therefore you add them to your own clients object in the connection listener and remove them in the disconnect listener.
I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}} might do the job.
You can use
//send message only to sender-client
socket.emit('message', 'check this');
//or you can send to all listeners including the sender
io.emit('message', 'check this');
//send to all listeners except the sender
socket.broadcast.emit('message', 'this is a message');
//or you can send it to a room
socket.broadcast.to('chatroom').emit('message', 'this is the message to all');
In 1.0 you should use:
io.sockets.connected[socketid].emit();
Whatever version we are using if we just console.log() the "io" object that we use in our server side nodejs code, [e.g. io.on('connection', function(socket) {...});], we can see that "io" is just an json object and there are many child objects where the socket id and socket objects are stored.
I am using socket.io version 1.3.5, btw.
If we look in the io object, it contains,
sockets:
{ name: '/',
server: [Circular],
sockets: [ [Object], [Object] ],
connected:
{ B5AC9w0sYmOGWe4fAAAA: [Object],
'hWzf97fmU-TIwwzWAAAB': [Object] },
here we can see the socketids "B5AC9w0sYmOGWe4fAAAA" etc. So, we can do,
io.sockets.connected[socketid].emit();
Again, on further inspection we can see segments like,
eio:
{ clients:
{ B5AC9w0sYmOGWe4fAAAA: [Object],
'hWzf97fmU-TIwwzWAAAB': [Object] },
So, we can retrieve a socket from here by doing
io.eio.clients[socketid].emit();
Also, under engine we have,
engine:
{ clients:
{ B5AC9w0sYmOGWe4fAAAA: [Object],
'hWzf97fmU-TIwwzWAAAB': [Object] },
So, we can also write,
io.engine.clients[socketid].emit();
So, I guess we can achieve our goal in any of the 3 ways I listed above,
io.sockets.connected[socketid].emit();
OR
io.eio.clients[socketid].emit();
OR
io.engine.clients[socketid].emit();
You can do this
On server.
global.io=require("socket.io")(server);
io.on("connection",function(client){
console.log("client is ",client.id);
//This is handle by current connected client
client.emit('messages',{hello:'world'})
//This is handle by every client
io.sockets.emit("data",{data:"This is handle by every client"})
app1.saveSession(client.id)
client.on("disconnect",function(){
app1.deleteSession(client.id)
console.log("client disconnected",client.id);
})
})
//And this is handle by particular client
var socketId=req.query.id
if(io.sockets.connected[socketId]!=null) {
io.sockets.connected[socketId].emit('particular User', {data: "Event response by particular user "});
}
And on client, it is very easy to handle.
var socket=io.connect("http://localhost:8080/")
socket.on("messages",function(data){
console.log("message is ",data);
//alert(data)
})
socket.on("data",function(data){
console.log("data is ",data);
//alert(data)
})
socket.on("particular User",function(data){
console.log("data from server ",data);
//alert(data)
})
As of version 1.4.5, be sure you provide a properly prefixed socketId in io.to().
I was taking the socketId the Client logged to debug and it was without prefix so I ended up searching forever till I found out! So you might have to do it like this if the Id you have is not prefixed:
io.to('/#' + socketId).emit('myevent', {foo: 'bar'});
io.sockets.sockets[socket.id].emit(...) worked for me in v0.9
Also you can keep clients refferences. But this makes your memmory busy.
Create an empty object and set your clients into it.
const myClientList = {};
server.on("connection", (socket) => {
console.info(`Client connected [id=${socket.id}]`);
myClientList[socket.id] = socket;
});
socket.on("disconnect", (socket) => {
delete myClientList[socket.id];
});
then call your specific client by id from the object
myClientList[specificId].emit("blabla","somedata");
Socket.IO allows you to “namespace” your sockets, which essentially means assigning different endpoints or paths.
This might help:
http://socket.io/docs/rooms-and-namespaces/

Categories