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.
Related
I'm trying to emit some message into a socket.io room using socket.io-mongodb-emitter. My problem is that, my script never exists, because it keeps a connection alive to mongodb.
Please check my examples below, and give me some advice, how can I make the script close mongodb connection and let itself exit.
emitter.js this script emits the message, the client gets it, but the process doesn't exit.
var io = require('socket.io-mongodb-emitter')("mongodb://localhost:27017/test");
io.in('someRoom').emit('someMessage');
emitter-2.js this script exits, but the client never gets the message.
var io = require('socket.io-mongodb-emitter')("mongodb://localhost:27017/test");
io.in('someRoom').emit('someMessage');
io.client.close();
emitter-3.js this one works perfectly, the client gets the message, and the process exits. But setTimeout is an extremely bad solution, there must be some proper way to let this process exit by itself.
var io = require('socket.io-mongodb-emitter')("mongodb://localhost:27017/test");
io.in('someRoom').emit('someMessage');
setTimeout(function () {
io.client.close();
},100);
Maybe use a callback to get an acknowledgement that the client received the message, then call the close function
server:
var message = "hello";
io.in('someRoom').emit('someMessage', message, function(data){
console.log(data);
io.client.close();
});
client:
socket.on('someMessage', function(message, callback){
// do something with message here
callback('message received');
});
You need to use the .emit's ability to receive an acknowledgement that the message was sent.
Do like so:
io.in('someRoom').emit('someMessage',function(){
console.log('message was sent');
io.client.close();
);
On Server you need to call the function when it is received.
socket.on('someMessage', function (name, fn) {
fn('received');
});
Documentation here
So, I'm setting up an express app, with all the usual goodies like passport, mongoose, connect-flash etc, and I'm using socket.io to listen for and emit messages.
Currently, I'm just emitting messages to everyone (will be setting up rooms later on) and everything (but this) is working great. When an end user visits any page, all currently connected users receive a message "Hi everyone!", and the user who just connected obviously sends them self the message too. All as expected so far...
The issue:
I have a page that has a button on it...
<button id="register" type="button" class="btn btn-warning">Register</button>
When clicked, this should emit a message saying 'I want to register!' (currently to everyone but that doesn't matter yet). In response, the server should listen for this and respond by emitting a message back saying 'Hmmm, will think about it!'.
'registering' is never heard at the server, and so cannot emit the reply of 'registration-response'.
Can anyone see what I'm doing wrong?
I've seen this SocketIO, can't send emit data from client and a couple others that are similar but I am already doing what they have suggested :/
NB: The app is running on http://localhost:3000/ and the io using http://localhost:8678/events. If you need any further info just let me know
Client-side JS/jQuery (app.js)
var app = app || {};
app = (function($){
$(function () {
/////////////////////////////////////////////////////
// Connect to io and setup listeners
/////////////////////////////////////////////////////
var socket = io.connect('http://localhost:8678/events');
socket.on('connected', function (data) {
console.log(data); // Always see this in the console
});
socket.on('registration-response', function (data) {
console.log(data); // NOT seen in console
});
/////////////////////////////////////////////////////
// Setup click events
/////////////////////////////////////////////////////
$('#register').on('click', function(){
console.log('click'); // Always see this, so no binding issue
socket.emit('registering', 'I want to register!');
});
});
})(jQuery);
Server-side JS
var app = require('express');
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server); //pass a http.Server instance
server.listen(8678); //listen on port 8678
////////////////////////////////////////
// Register event listeners
////////////////////////////////////////
var events = io.of('/events');
events.on('connection', function(socket){ // This is heard and callback fires
events.emit('connected', 'Hi everyone!'); // This gets sent fine
});
events.on('registering', function(data){
events.emit('registration-response', 'Hmmm, will think about it!');
});
Your socket on the server isn't set up to listen for the event.
You need to do it like this
events.on('connection', function(socket){ // This is heard and callback fires
events.emit('connected', 'Hi everyone!'); // This gets sent fine
socket.on('registering', function(data){
events.emit('registration-response', 'Hmmm, will think about it!');
});
});
The socket now knows what to do when it receives the 'registering' event and will send the response to the '/events' namespace.
Whenever I disconnect using socket.disconnect(); and then reconnect using socket.connect();, the server runs my handshake code twice. The strange thing is, even though the server connection code runs twice, there is only one connection in my array after reconnecting. This happens on an accidental disconnection, intentional, or even if the server restarts. Bit of code:
io.on('connection', OnConnect);
function OnConnect(socket) {
var connection = { socket: socket, realIp: ip, token: GenerateConnToken() };
connections.push(connection);
console.log('Connected');
// Client will respond to this by emitting "client-send-info".
// This is emitted once on initial connect, but twice on reconnect.
socket.emit('acknowledge', connection.token);
socket.on('client-send-info', function() {
console.log('Client Sent Info');
});
socket.on('disconnect', function() {
console.log('Disconnected');
});
}
The above code, when a client connects, disconnects, and then reconnects once, will produce the following log:
Connected
Client Sent Info
Disconnected
Connected
Client Sent Info
Client Sent Info
Why is it that, when reconnecting, the connection code will run twice, but only create one connection object?
EDIT: Upon further inspection, it seems that a different piece of my connection code is being performed twice when the client reconnects. The above code is updated to reflect the relevant information.
Strangely, the solution is completely client side. Instead of the following code:
var socket = io.connect();
socket.on('connect' function() {
socket.on('acknowledge', function() {
});
});
You have to use:
var socket = io.connect();
socket.on('connect' function() {
});
socket.on('acknowledge', function() {
});
Otherwise, the server will appear to be sending multiple emits when it is in reality only sending one, and it's the client that falsely receives multiples. With the second code format, the client successfully connects initially, disconnects, and reconnects without receiving multiple emits.
Simply, don't put any additional socket.on('x') calls inside the on('connection') call. Leave them all outside it.
This code works great and connects to the socket server that I have running:
var socket = io('http://localhost:8888');
socket.on('news', function (data) {
console.log(data);
socket.emit('evento', { my: 'data' });
});
socket.on('disconnect', function () {
console.log('user disconnected');
});
socket.on('connect', function () {
console.log('user connect');
var data = 'ddsds';
socket.emit('evento', { my: 'data' });
});
On the other hand when I try to use WebSocket() it fails to connect. This is the code that doesn't work:
var socket = new WebSocket('ws://localhost:8888');
// Open the socket
socket.onopen = function(event) {
// Send an initial message
socket.send('I am the client and Im listening!');
}
// Listen for messages
socket.onmessage = function(event) {
console.log('Client received a message',event);
};
// Listen for socket closes
socket.onclose = function(event) {
console.log('Client notified socket has closed',event);
};
socket.onerror = function(event) {
console.log('error: ',event);
};
It's not an error in the code; I think there is a different way to connect. I need this to work using WebSocket();. Any help would be greatly appreciated!!
socket.io is something that runs on top of WebSocket (using WebSocket as one of the transports it supports). It adds new semantics on top of WebSocket so you can't use the socket.io methods and events directly with a WebSocket object.
socket.io will select the WebSocket transport if it is available so you should not need to use your second example - the first should work just fine and will use WebSockets automatically (when available).
See this answer and this answer for how to use the minimized, gzipped and cached version of socket.io which makes it smaller and faster.
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
});