Switch socket server on disconnect - socket.io

I am trying to connect a new server when the first server is down and attempted in reconnect_failed. Upto now it is working fine, first server disconnects, second server connected and listening the message.
socket.on('reconnect_failed', function () {
console.log("reconnect_failed");
socket = io.connect('http://localhost:4000',{
'reconnectionDelay': 100,
'reconnect':false,
'reconnectionAttempts': max_reconnects});
console.log(socket);
});
socket.on('new message', function(msg){
console.log(msg);
document.getElementById("chat").innerHTML = msg;
});
But at the client side "new message" event is not listened by second server. Due to that socket is initiated inside reconnect failed. Is there any other way to process with less code.

What I would do is have a function to switch server on disconnection.
Something like :
function initSocket(i){
sockets = io.connect(servers[i], {
'reconnectionDelay': 100,
'reconnect':false,
'reconnectionAttempts': max_reconnects});
sockets.on("connection", function(socket){
socket.on('connect',function(data){});
socket.on('new message', function(msg){
console.log(msg);
document.getElementById("chat").innerHTML = msg;
});
socket.on('reconnect_failed', function () {
console.log("reconnect_failed");
i==0 ? 1 : 0; //switch the value of i
initSocket(i) //init a socket on the other server
});
});
}
var servers = ["http://localhost:3000","http://localhost:4000"];
initSocket(0); //start with server 0 (http://localhost:3000)
This should give you the switch between your 2 servers on disconnect, with the exact same properties and event listeners. When one crashes, the other takes over.

Related

Socket.io don't emit after disconnect event

I want to send data from the server to the client after a disconnect socket.io event occurs.
Server :
const clients = {};
io.on('connection', socket => {
clients[socket.id] = socket;
console.log('connect : ' + socket.id);
socket.emit('socket-connect', 'connected');
socket.on('disconnect', () => {
socket.emit('socket-disconnect', 'disconnected');
delete clients[socket.id];
console.log('disconnect : ' + socket.id);
});
});
Client :
const socket = openSocket('localhost');
socket.on('socket-connect', data => {
console.log(data);
});
socket.on('socket-disconnect', data => {
console.log(data);
});
If socket connected, the server send a connect message to client and it works, but it does not send interrupted messages to the client if the disconnection occurs.
console.log('disconnect : ' + socket.id); on server showing disconnect with the socket.id.
I'm using socket.io v2.0.4 both on server and client.
How can I send data from the server if a socket disconnect event occurs?
Event: disconnect is fired upon disconnection. This simply means, for some reason, there is no connection between the client and the server.
So in this situation, you cannot send data to the client as the client is not connected. Disconnection may happen if the client's network is not available(read Internet failure) or the client environment(ex: browser) crashed or the user closed the tab.

Socketio: How can i send a single string over to the client

I am trying to send a string to the client like this:
socket.emit("start", "calm");
but it is throwing an error, is it because it is not an object ?
First thing first, you should make sure your socket between server-side and client-side is connect. And register event and function to the socket.
Server-side
io.sockets.on('connection', function(socket) {
console.log('socket connect' + socket.id);
// when a client connect to server within socket, server will send hello
io.emit('newMsg', "hello")
socket.on('disconnect', function() {
console.log('socket disconnect');
})
// when server receive a message, it will send to all client which connect
to the server
socket.on('data', function (data) {
console.log(socket.id +': ' + data.msg);
var message = {from: socket.id,
msg: data.msg
}
io.emit('newMsg', message)
})
}
Client-side
var socket = io('http://localhost:3000');
socket.on('connect', function (data) {
console.log(data)
})
socket.on('newMsg', function(data) {
console.log(data)
})
// function could bind on button on client side page, get input and send data
function sendData() {
var input = document.getElementsByTagName('input')
var text = input[0].value
var data = { msg: text }
socket.emit('data', data)
}
open console, the information would show in the console. When sending a message on server-side, could use 'broadcast' instead of 'emit' as well to send the message to other clients except you. Read the doc: socket.io doc

Socket.emit() outside socket.on()

Do we always have to use socket.emit() inside a socket.on() like that:
io.sockets.on('connection', function (socket) {
console.log('User connected !');
retrieveDictionnary((dictionnary) =>{
socket.emit('dictionnarySend', dictionnary);
}
}
I want to create on my client side a function which ask information to the server when I click on a button:
translateServer(parameter, control){
this.socket.emit('translate', [parameter,control]);
}
But it seems that it's not working, the server never receive this message.
Thank you !
The pattern you are using above is the recommended way of interacting with a socket (ie acquiring a socket instance when the 'connection' event fires, and then calling emit() from that socket instance, etc).
If I understand your client-side requirements correctly, you are wanting to send data to the server via web sockets - are you sure the socket that you have established a web socket connection between the client and server?
For instance, if you add the following to your client-side code, you should see a success message in your console:
const socket = io.connect('YOUR SERVER ADDRESS');
socket.on('connect', () => {
console.log('connected to server!');
// [UPDATE]
// This assumes you have a <button> element on your page. When
// clicked, a message will be sent to the server via sockets
document.querySelector('button').addEventListener('click', (event) => {
// Prevent button click reloading page
event.preventDefault();
// Send message to server via socket
socket.emit('MESSAGE_ID', 'test message from client' + new Date());
});
});
Update
This shows your original server code, expanded with the detail needed to receive and print data sent from client via sockets:
io.sockets.on('connection', function (socket) {
console.log('User connected !');
// Register a server handler for any messages from client on MESSAGE_ID channel
socket.on('MESSAGE_ID', (message) => {
// Print the message received from client in console
console.log('message from client', message);
})
retrieveDictionnary((dictionnary) =>{
socket.emit('dictionnarySend', dictionnary);
}
}

Socket.io client only joins room on every other connection

I've been trying to make a basic notification system that uses rooms in Socket.io. However, for some reason, it only works every other time you refresh the page.
I've simplified the code to make it easier to debug, but the issue remains. Each time I refresh the page, everything seems to work except joining a room (which only works half the time). What could be going on?
edit: I'm using Socket.io version 1.1.0 and Node.js version 0.10.31
edit2: Added FunnyLookinHat's suggestion (but it still doesn't solve the problem)
Client-Side Code:
socket = io.connect('example.com:8081'),
socket.on('connect', function () {
socket.on('startup', function(data) {
console.log(data.message);
});
socket.emit('joinRoom');
});
Server-Side Code:
var io = require('socket.io').listen(8081);
io.sockets.on('connection', function (socket) {
console.log(socket.id + ' connected!');
socket.emit('startup', { message: 'Socket started!' });
socket.on('joinRoom', function(){
console.log(socket.id + ' joining room lobby'); // prints on every other request
socket.join('lobby');
});
socket.on('disconnect', function() {
console.log(socket.id + ' disconnected!');
});
});
Client Console:
Socket started!
(refreshed page)
Socket started!
Server Console:
UIBqVuOiF1fegMIMAAAB connected!
UIBqVuOiF1fegMIMAAAB joining room lobby
UIBqVuOiF1fegMIMAAAB disconnected!
(refreshed page)
x3nMilBOjjFVjBFJAAAC connected!
(after about a minute once the client window has been closed or refreshed)
x3nMilBOjjFVjBFJAAAC disconnected!
Race condition! Try doing the following in your client code:
socket = io.connect('example.com:8081'),
socket.on('connect', function () {
socket.on('startup', function(data) {
console.log(data.message);
});
socket.emit('joinRoom');
});

Websocket messages mysteriously disappear

I'm going crazy trying to figure out what's wrong with my system that it is unable to send websocket messages. I've tried a ton of things:
Chrome 32, firefox 27, ie 10
various websocket server libraries: ws, websocket, nodejs-websocket
running the server on windows and centos
reinstalling node.js (to version 0.10.26)
reinstalling firefox
Turning off my firewall
The behavior is always the same: both client and server say they get a connection, but when the client tries to send a message, the other one simply doesn't get it. Sometimes i get "Error: read ECONNRESET" on the server - but not all the time. About 50% of the time it just fails silently. Eventually the connection closes.
If I add code to send a message from the server on connection, it always gets "Error: read ECONNRESET".
What does work?
the exact same code and setup on my laptop
any websocket code online, for example this: http://www.websocket.org/echo.html
So what could cause just my local websocket connection to silently drop messages?
Server:
var
ws = require('websocket').server
var http = require('http')
var server = http.createServer(function(request, response) {
console.log("connection received for "+request.url)
response.writeHead(404)
response.end()
})
server.listen(8080, function() {
console.log("now listening")
})
wsServer = new ws({httpServer:server, autoAcceptConnections: false})
wsServer.on('request', function(request) {
console.log("got request")
var connection = request.accept('a', request.origin)
console.log("got connection")
connection.on('message', function(message) {
console.log("got message: "+message)
})
connection.on("close", function() {
console.log("closed")
})
connection.on('error', function(e) {
console.log('Error: '+e)
})
})
Output:
got connection
closed
Client:
<script>
var ws = new WebSocket('ws://localhost:8080/', 'a')
ws.onopen = function() {
console.log('open')
ws.send('something2')
}
ws.onerror = function(e) {
console.log(e)
}
ws.onmessage = function(m) {
console.log(m)
}
ws.onclose = function() {
console.log('closed')
}
</script>
Output
open
closed
This is driving me crazy.

Resources