Reconnection in socket.io problem in `socket.on('message',function(){})` - javascript

I have a socket.io connection to connect to server and client,
It work fine.
Now when I try to reconnect it on disconnect from server it get connected but then socket.on('message' doesnt get fired any more.
I checked it from server side it is pushing that message.
Please suggest me some thing I am out of ideas now.
I am sure that problem is on client side socket.on message
Client side code
var socket = new io.Socket('some host name',{port:80,rememberTransport:true});
socket.on('connect', function(){
clearInterval(socketInterval);
});
socket.on('message', function(obj)
{
alert("meg from server");
});
socket.on('disconnect', function()
{
socketInterval=setInterval("socket.connect()",5000);
});
socket.connect();

I don't know node.js, but it looks like syntax error, haven't you forgot the right paratheses?
socket.on('connect', function(){
clearInterval(socketInterval);
});
socket.on('message', function(obj)
{
alert("meg from server");
});
socket.on('disconnect', function()
{
socketInterval=setInterval("socket.connect()",5000);
});

it would appear that the "problem" most likely is on the server side. The server has two ways to send messages to the client (emit and broadcast). If you are doing a one to one message, most people use emit. I am assuming that you built a chat server which stores the sessionIds of the client. It works fine with the initial connection because the server has the correct sessionId, but let's say connection is lost and you reestablish connection, now the server tries to send a message to the client. If your server stored the initial sessionId, say in an array, and attempts to use the original sessionId to emit a message, it will fail because reconnection causes a new sessionId to be created.
The solution in this case is to remove the previous sessionId from the array and add the new sessionId upon reconnection.

Related

How to Callback socket.io client using sails.sockets.js onconnect event?

Am not able to call socket-client listener using sails.sockets.js onConnect event on server side..
E.g
onConnect: function(session, socket) {
socket.on('chat message', function(msg){
console.log(msg);
console.log("socket.id: " + socket.id);
sails.sockets.broadcast(socket.id, 'chat message', {msg:msg});
});
}
Please let me know whats the correct way of calling back to your socket-client using socket-server events like onConnect..
If you are using standard sails.js socket library:
$(document).ready(function() {
io.socket.on('connect', function() {
});
io.socket.on('chat message', function(data) {
io.socket.post('/routeToAction', {
}, function(data, jwres) {
});
});
});
for newer version, you have to use config/bootstrap.js file for listen events
module.exports.bootstrap = function(cb) {
// handle connect socket first event executes after logged in
sails.io.on('connect', function (socket){
// store facebook token here
});
// handle custom listener for other stuff
sails.io.on('doSomeStuff', function (socket){
// check facebook token match with requested token
});
cb();
};
client : you can simple emit "doSomeStuff" after logged in with facebook and pass token with each request
Finally am become little expert in web sockets who knows back anf forth of push technoligy via websockets..
How to start with websockets :
Step 1: Choose any websocket framework for your application and install socket client on client side and socker server on server side with listeners(imp.).
Step 2: Once you are ready with socket setup on both sides then your client/browser will make a connection after every page load which is listened on server side via onConnect listener or event.
Step 3: Successfull connection on both sides giving you socket object which contains each client socket id which is managed at server side to either join any channel/room or just to make a broadcast or blast.
Remember:
i. Socket object is responsible for defining listeners on both client side and server side. Using socket object you can pass any data to listeners.
ii. Socket connection is very helpful when you trying to push data from client to server and vice-versa.
iii. You can make your small chatter tool with it once you understand as mentioned above.
Will share similar working snippet soon..
//onConnect event on server side
onConnect: function(session, socket) {
console.log("Socket Connect Successfully: " + socket.id );
socket.on('chatAgency', function(data){
sails.sockets.broadcast(data.agencyId,"chatAgency", {message:data.message,agencyId:session.agencyId});
});
},

Socket.IO: Reconnect Causes Server Connect Code to Run Twice

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.

Socketio send message to specific client in namespace

server side:
io.of('/lobby').on('connection', function(client) {
setInterval(function(){
io.to(client.id).emit('message','test');
},2000);
});
client side:
var ioLobby = io.connect('127.0.0.1:9001/lobby');
ioLobby.on('message',function(data){
console.log(data);
});
I'm trying to send a message to a specific client in socket.io version 1.2.1. I've verified that the socket joins the default room on the server side, but its not being triggered on the client side. Any ideas?
The line io.to(client.id) will only work if that user has first joined a room with that same name. You need something like
io.on('connection', function(socket){
socket.join('some room');
});
and then you can call io.to
io.to('some room').emit('some event'):
I compromised and ended up using
socket.emit()
The only downside in comparison is requiring a ref to the socket you're emitting to.

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

Is there a way for client to send server data on socket disconnection?

Is it possible for client to send a socket data when it gets
disconnected (user closes the browser, or tab)?
Because, I found that default bind on disconnect doesn't take any input data.
//on server side
socket.on('disconnect',function(){
//in other binds, it takes 'data' as an input but this does not
});
I tried to resolve this problem by using the jQuery's unload method
like below
//on client side
$(window).unload(function(){
socket.emit('depart','I am leaving');
});
However, it does not seem to emit at all on unload. (maybe socket gets out of scope on unload?)
Is there a way to send data through websocket to the server when client disconnects?
Secondly, Is there any way that I can store a string data in socket? For instance,
socket.userName = userNameVar;
--update--
Here is how I set up environment on the serverside
io.sockets.on('connection',function(socket){
socket.on('depart',function(data){
console.log(data);
console.log("user left");
});
socket.on('disconnect',function(){
console.log("user disconnected");
});
});
and following code is in the client side.
var socket = io.connect(hostVar);
$(window).unload(function(){
socket.emit('depart','I am leaving');
});
The reason you cannot send data on disconnect is because you are disconnected. What you are asking is somewhat akin to saying "Can i still talk to the person on the phone after they've hung up on me?"
If you want to emit the 'depart' event, then you still have to capture it inside your 'connect' handler on server side:
As in:
io.socket.on('connection', function(socket) {
socket.on('depart', function(msg) {
// you should get depart message here
});
})
Your depart event will come BEFORE the connection is terminated. disconnect is only raised by server upon a successful disconnection and therefore it cannot receive any messages.
Give it a try and tell me if this works :)
Use this instead
$(window).on('beforeunload',()=>{
socket.emit('page_unload');
});
and on server side
io.socket.on('connection', function(socket) {
socket.on('page_unload', function(msg) {
// client has reloaded page or closed page
});
})

Categories