socket.io not reconnecting after a disconnect - javascript

I am developing a node.js application using socket.io to communicate between server and client. If the server faces any error, I send an error message to the client and I close the connection from both server and client. However when the client tries to reconnect, it is no longer able to connect to the server. My code
server.js
io.sockets.on('connection', function(socket) {
/*Some code*/
stream.on('error',function(errormsg){
socket.emit('error',{txt: "Error!"});
socket.disconnect();
});
});
client.js
var server_name = "http://127.0.0.1:5000/";
var socket = io.connect(server_name);
socket.on('error',function(data){
console.log(data.txt);
socket.disconnect();
});
function submitclick()
{
var text="hello";
if(socket.connected ==false)
socket= io.connect({'forceNew': true});
console.log(socket.connected);
}
Status of socket.connected is false. I do not receive it on the server side either.

I don't think your call to io.conncet is synchronous, you're checking socket.connected too early. If you want to verify that your reconnect succeeds, try it like this:
function submitclick()
{
var text="hello";
if(socket.connected ==false) {
socket= io.connect({'forceNew': true});
socket.on('connect', function() {
console.log('Connected!');
});
}
}
Edit:
As #jfriend00 points out there's probably no need for you to do the socket.disconnect() in the first place as socket.io should automatically be handling reconnection.

Related

Why does my socket.io app disconnect immediately when run on Raspberry pi?

I am attempting to build a node.js application on a Raspberry Pi which can communicate with a remote socket.io server.
The socket.io server quite simply writes to the console when a new connection is established and when an existing connection is closed.
The socket.io client works as expected when run in a browser.
However, when I run the client code from a Raspberry Pi it connects and immediately terminates. This does not allow me to perform any function such as emitting or receiving.
The on connect event is never fired.
var io = require('/usr/local/lib/node_modules/socket.io-client');
var serverUrl = 'http://remoteserver.com';
console.log('Connecting to ' + serverUrl);
var socket = io.connect(serverUrl);
socket.on('connect', function(socket) {
console.log('Connection established!');
console.log(socket.id);
socket.on('disconnect', function() {
console.log('Disconnected from server');
});
});
The code above will output:
Connecting to: http://remoteserver.com
On the server side, the output will show a new connection and eventually a timeout close.
Why is the client on connect event not firing? How can I persist this connection so that I can eventually send inputs to the server?
Remove the line:
socket.close();
from your code. You are closing the socket immediately. Remember that all the event handlers are asynchronous. They are non-blocking and will be called some time in the future. Meanwhile, the rest of your code runs to completion and thus your socket.close() is executed before your client has any chance to get any events (other than the disconnect event).
If you want to do some stuff and then close the socket, then you need to close the socket only from some event handler that indicates that your operation is complete and you are now done with the socket.
You only need to call socket.close() when you want to close the connection from the raspberry pi. Also, the socket.io-client documentation does not use the .connect method, but instead calls require('socket.io-client')(serverUrl)
var io = require('/usr/local/lib/node_modules/socket.io-client');
var serverUrl = 'http://remoteserver.com';
console.log('Connecting to ' + serverUrl);
var socket = io(serverUrl);
socket.on('connect', function(socket) {
console.log('Connection established!');
console.log(socket.id);
});
socket.on('disconnect', function() {
console.log('Disconnected from server');
});
//Removed the socket.close() line

socket.io emit/broadcast to every client

I can not find out how to emit from the client or an other NodeJS file to every client.
Emitting to the server worked, but not to every other client.
Servercode:
var io = require('socket.io').listen(app.listen(8080));
io.on('connection', function (socket) {
socket.on('playerData', function(data) {
console.log(data);
});
});
Clientcode:
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script>
var socket = io('http://localhost:8080');
socket.on('playerData', function(data) {
console.log(data);
});
</script>
I am using Node.JS - Jade, Express, Socket.io (and AngularJS, but not in this part of the code)
The Serverside console.log is being called when I call my emit function, but on the Clientside nothing happens.
Currently using Chrome as my browser.
You need to emit from the client to the server and then broadcast that message from the server to each client.

Why don't I see a response from socket.io-client with node.js?

var io = require('socket.io-client'),
socket = io.connect('targeturl', {
port: 8080
});
socket.on('connect', function () {
console.log("socket connected"); //this is printed.
});
socket.emit('list', {"user":'username',"token": 'mytoken'});
socket.on('message', function(data){
console.log(data);
});
socket.on('error', function(data){
console.log(data); //nothing is printed
});
I see the message 'socket connected' when running this from node.js on the command line but I don't see a response from the 'list' call.
Note that this is a specific question about using socket-io-client from Node.js as a command line application.
I have verified using curl that I can reach the socket server which is REMOTE i.e I do not have the server code but I know that it uses socket.io.
I'm no expert on the matter, but it appears you're attempting to emit the message before the connection is established. (This stuff is asynchronous after all.)
Try moving the emit call inside of the handler for the 'connect' event, to ensure that it happens afterward.

Node.js: socket.io close client connection

How can I close the socket connection on the client side?
I am using:
socket.io 0.9
node.js 0.10.15
express 3.3.4
i.e.:
call localhost/test
-- server side
var test = io
.of('/test')
.on('connection', function (socket) {
console.log('open socket: ' + socket);
socket.on('disconnect', function () {
console.log('disconnected event');
//socket.manager.onClientDisconnect(socket.id); --> endless loop with this disconnect event on server side
//socket.disconnect(); --> same here
});
});
-- client side
var socket = io.connect('http://localhost:3000/test');
socket.on('disconnect', function () {
console.log('disconnect client event....');
});
socket.emit('getInitData', function (data) {
.. do something with data
});
If I load the test-page I need some values from the server (getInitData).
On the first page visit I get the data once, on a reload or second visit I get it twice and so on.
The connection on the server side is beeing closed automatically on page reload and if you leave the page.
But on the client side the connection is still open.
How can I close the connection on the client side or check if there is already a open connection?
UPDATE
I tried now the following: (client side)
window.onbeforeunload = function(e) {
socket.disconnect();
};
This triggers on the client side the disconnect event, but I still get the twice or tripple response.
Did you try:
socket.disconnect()
on client?
For socket.io version 1.4.5:
On server:
socket.on('end', function (){
socket.disconnect(0);
});
On client:
var socket = io();
socket.emit('end');
There is no such thing as connection on server side and/or browser side. There is only one connection. If one of the sides closes it, then it is closed (and you cannot push data to a connection that is closed obviously).
Now a browser closes the connection when you leave the page (it does not depend on the library/language/OS you are using on the sever-side). This is at least true for WebSockets (it might not be true for long polling because of keep-alive but hopefuly socket.io handles this correctly).
If a problem like this happens, then I'm pretty sure that there's a bug in your own code (on the server side). Possibly you are stacking some event handlers where you should not.
socket.disconnect()
Only reboots the connection firing disconnect event on client side. But gets connected again.
socket.close()
Disconnect the connection from client. The client will keep trying to connect.
socket.disconnect() is a synonym to socket.close() which disconnect the socket manually.
When you type in client side :
const socket = io('http://localhost');
this will open a connection with autoConnect: true , so the lib will try to reconnect again when you disconnect the socket from server, to disable the autoConnection:
const socket = io('http://localhost', {autoConnect: false});
socket.open();// synonym to socket.connect()
And if you want you can manually reconnect:
socket.on('disconnect', () => {
socket.open();
});
I'm trying to close users connection in version 1.0 and found this method:
socket.conn.close()
The difference between this method and disconnect() is that the client will keep trying to reconnect to the server.
try this to close the connection:
socket.close();
and if you want to open it again:
socket.connect();
Just try socket.disconnect(true) on the server side by emitting any event from the client side.

Socket IO Server to Server

Is it possible for a server to connect to another using Socket.IO and be treated like a client?
And have it join rooms, recieve io.sockets.in('lobby').emit(). And more?
The first server is also listening for connections/messages as well.
Hey Brad, here's my full .js app below for reference:
var io = require("socket.io").listen(8099);
io.set('log level', 1);
io.sockets.on("connection", function (socket) {
console.log('A Client has Connected to this Server');
//Let Everyone Know I just Joined
socket.broadcast.to('lobby').emit("message",'UC,' + socket.id); // Send to everyone in Room but NOT me
socket.on("message", function (data) {
//Missing code
socket2.send('message,' + data); //Forward Message to Second Server
});
socket.on("disconnect", function (data) {
//Send Notification to Second Server
//Need to figure out later
//Send Notification to Everyone
socket.broadcast.emit("message",'UD,' + socket.id ); //Send to Everyone but NOT me
//Remove user from Session ID
arSessionIDs.removeByValue(socket.id);
//Send Notification to Console
console.log("disconnecting " + arRoster[socket.id][1]);
});
});
var io_client = require( 'socket.io-client' );
var socket2 = io_client.connect('http://192.168.0.104:8090');
socket2.on('connect', function () {
socket2.emit('C3434M,Test');
});
Yes, absolutely. Just use the Socket.IO client in your server application directly.
https://github.com/LearnBoost/socket.io-client
You can install it with npm install socket.io-client. Then to use:
var socket = io.connect('http://example.com');
socket.on('connect', function () {
// socket connected
socket.emit('server custom event', { my: 'data' });
});
I realize this is an old post, but I was working on something similar and decided to come back and contribute something as it got me thinking.
Here's a basic Client -> Server 1 -> Server 2 setup
Server #1
// Server 1
var io = require("socket.io").listen(8099); // This is the Server for SERVER 1
var other_server = require("socket.io-client")('http://example.com:8100'); // This is a client connecting to the SERVER 2
other_server.on("connect",function(){
other_server.on('message',function(data){
// We received a message from Server 2
// We are going to forward/broadcast that message to the "Lobby" room
io.to('lobby').emit('message',data);
});
});
io.sockets.on("connection",function(socket){
// Display a connected message
console.log("User-Client Connected!");
// Lets force this connection into the lobby room.
socket.join('lobby');
// Some roster/user management logic to track them
// This would be upto you to add :)
// When we receive a message...
socket.on("message",function(data){
// We need to just forward this message to our other guy
// We are literally just forwarding the whole data packet
other_server.emit("message",data);
});
socket.on("disconnect",function(data){
// We need to notify Server 2 that the client has disconnected
other_server.emit("message","UD,"+socket.id);
// Other logic you may or may not want
// Your other disconnect code here
});
});
And here's Server #2
// Server 2
var io = require("socket.io").listen(8100);
io.sockets.on("connection",function(socket){
// Display a connected message
console.log("Server-Client Connected!");
// When we receive a message...
socket.on("message",function(data){
// We got a message. I don't know, what we should do with this
});
});
This is our Client, who sends the original message.
// Client
var socket = io('http://localhost');
socket.on('connect', function(){
socket.emit("message","This is my message");
socket.on('message',function(data){
console.log("We got a message: ",data);
});
});
I am making this post a Community Wiki so that someone can improve this if they feel like it.
The code has not been tested, use at your own risk.
I had the same problem, but instead to use socket.io-client I decided to use a more simple approach (at least for me) using redis pub/sub, the result is pretty simple.
You can take a look at my solution here: https://github.com/alissonperez/scalable-socket-io-server
With this solution you can have how much process/servers you want (using auto-scaling solution), you just use redis as a way to forward your messages between your servers.

Categories

Resources