I am working on socket.io and i am new to this. I am trying to disconnect after n number of attempts to reconnect.
Server Side Code:
var io = require('socket.io').listen(4000);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Client side code is:
<script src="http://localhost:4000/socket.io/socket.io.js"></script>
<script>
//var max_reconnects, socket;
var max_reconnects = 5;
var socket = io.connect('http://localhost:4000',
{'reconnection delay': 100,
'max reconnection attempts': max_reconnects,
'reconnection limit' : 10});
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
socket.on("reconnecting", function(delay, attempt) {
console.log("attempting reconnect - " + attempt + "-->" + delay);
if (delay === max_reconnects) {
//return console.log("all reconnect attempts failed");
//socket.disconnect();
//socket.server.close();
socket.emit('forceDisconnect');
console.log("Limited end");
}
});
Please guide me how to terminate the reconnecting activity after number of attempts. the given code is not working properly. and reconnecting call back attempts is also undefined. Please guide me
Are you using socket.io >= 1.0 but using an example from before (there were some changes)?
Check here for the correct parameters: https://github.com/Automattic/socket.io-client#managerurlstring-optsobject
var socket = io.connect('http://localhost:4000',
{'reconnectionDelay': 100,
'reconnectionAttempts': max_reconnects});
Related
-----------------------------client socket ----------------------
$(document).ready(function () {
var socket = io.connect('http://localhost:8282');
$('#stopbtn').click(function(){
socket.emit('RandomStatus',{message:'stop'});
})
$('#startbtn').click(function(){
socket.emit('RandomStatus',{message:'start'});
})
});
----------------------------------Nodejs server --------------------
var io = require('socket.io').listen(app.listen(8282));
io.set('log level', 1);
var randomizerjson = require('./randomizerjson');
io.sockets.on('connection', function (socket) {
var intervalId;
socket.on('RandomStatus', function (data) {
var status = data.message;
if(status=='start'){
//random data after 700 milisecond and send
intervalId= setInterval(function () {
var randomData = randomizerjson.getRandomData1();
//send random data somewhere
io.sockets.emit('dataSet', randomData);
}, 700);
}
if(status=='stop'){
clearInterval(intervalId);
}
});
socket.on('disconnect', function () {
console.log('user disconnect');
});
});
When I click start button, I can send random data. But when I click stop button, I can not clearInterval to stop sending random data.
I want to stop sending random data when I receive 'stop' message, but that's not working. Can anyone help me and tell me why?
I've wrote a simple app and tested in Chrome. All works fine!
Now I'm testing with qupzilla, but when I trigger the .emit function, nothing happens!
From chrome i wrote a thing, the object is updated and sent to server, server does a broadcast. All fine (qupzilla receives the update too).
But, if I write something on qupzilla, this update isn't sent to server (No logs in node)
Here's some code.
Server side:
var io = require('socket.io').listen(8080);
io.set("log level", 1);
var dataStored = [];
io.sockets.on('connection', function (socket) {
socket.emit('event', dataStored);
socket.on('update', function (data) {
console.log(data);
dataStored = data;
socket.broadcast.emit("event", data);
});
});
And client side:
$scope.things = [];
$scope.pushingObj = "";
// socket
var socket = io.connect("http://localhost:8080", {
'connect timeout': 500,
reconnect: true,
'reconnection delay': 500,
'reopen delay': 500,
'max reconnection attempts': 10000
});
socket.on("event", function(data) {
$scope.things = data;
$scope.$apply();
});
//
$scope.pushObj = function() {
//console.log($scope.pushingObj);
$scope.things.push($scope.pushingObj);
socket.emit("update", $scope.things);
$scope.pushingObj = "";
}
I am building a game using socketio.
The server stores the number of players, when it goes to 2, game start.
However, when I open two browser one by one, only the first one(not the latter one) receive the game start message.
Client side:
var socket = io.connect('http://localhost:8080');
socket.on('connected', function (data) {
$('#status').html('You are connected');
socket.emit('1 party connected');
});
socket.on('game start', function (data) {
$('#status').html('game start');
});
Server side:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8080);
var connected_parties_no = 0;
io.sockets.on('connection', function (socket) {
socket.emit('connected', { hello: 'world' });
socket.on('1 party connected', function () {
connected_parties_no++;
console.log(connected_parties_no.toString()+' parties are connecting.');
if (connected_parties_no == 2) {
game_start(socket);
}
});
socket.on('disconnect', function () {
connected_parties_no--;
});
});
function game_start(socket) {
socket.broadcast.emit('game start');
}
socket.broadcast.emit('game start');
will send the 'game start' event to everyone except `socket. You're most likely looking for
io.sockets.emit('game start');
With node.js, I'm trying to send the current server_time to all clients in every second.
Therefore, I wanted to use setInterval() to emit an event to all clients and sending the time, but it doesn't work. Did I define the setInterval function at the right place or did missed something else?
var http = require("http");
var socketIO = require('socket.io');
var connect = require('connect');
//keep track of every connected client
var clients = {};
//create Server
var httpServer = connect.createServer(
connect.static(__dirname)
).listen(8888);
//socket
var io = socketIO.listen(httpServer);
io.sockets.on('connection', function (socket) {
//add current client id to array
clients[socket.id] = socket;
socket.on('close', function() {
delete clients[socket.fd]; // remove the client.
});
//send news on connection to client
socket.emit('news', { hello: 'world' });
//this one works fine!
//send server time on connection to client
socket.emit("server_time", { time: new Date().toString() });
});
//this doesn't work!
// Write the time to all clients every second.
setInterval(function() {
var i, sock;
for (i in clients) {
sock = clients[i];
if (sock.writable) { // in case it closed while we are iterating.
sock.emit("server_time", {
console.log("server_time sended");
time: new Date().toString()
});
}
}
}, 1000); //every second
May I suggest a workaround/improvement that should fix the problem. Add the clients to a chat room. Somewhere in:
io.sockets.on('connection', function (socket) {
add a
socket.join('timer');
Then the setIntervall would be
setInterval(function() {
io.sockets.in('timer').emit("server_time", { time: new Date().toString() })
}, 1000);
Hope this works for you!
The problem is the following function:
if (sock.writable) { // in case it closed while we are iterating.
sock.emit("server_time", {
// console.log("server_time sended"); // get rid of this line -> invalid code
time: new Date().toString()
});
}
sock.writable is undefined and therefore the emit event is never sent. Set the property to true on connection and to false on close.
Im trying to create a NodeJS TCP Server, that will read to the clients input and then act accordingly.
I'd like to know how I can read the data, so I can set up conditionals to perform process.
var net = require('net');
var server = net.createServer(function (socket) {
socket.on('data', function(data) {
buf = new Buffer(256);
len = buf.write(data.toString());
if (buf.toString('utf8', 0, len) === "test"){
console.log("you typed test");
}
console.log(len + " bytes: " + buf.toString('utf8', 0, len));
});
socket.write("Connected to server.\r\n");
});
server.listen(8080, "127.0.0.1");
I am outputting the value inputted here :
console.log(len + " bytes: " + buf.toString('utf8', 0, len));
but my if statement above this log, isnt matching the value 'test' when I actually type 'test' in the client terminal window.
Any help is appreciated
-chris
I worked it out using the toString() method:
socket.on('data', function(data) {
var response = data.toString().trim();
if (/disconnect/.test(response)) {
console.log("Client is diconnecting.");
socket.end('Disconnecting you now.\r\n');
}
});
socket.on('end', function() {
console.log('client disconnected');
});