Good day,
I was playing with the example found here on SO: PHP Socket Server vs node.js: Web Chat.
Using gMUD (a telnet-like client) to connect to my server, I can't seem to be able to detect when the client disconnect from the server.
Here is the two events I'm using:
socket.on('end', function() {
console.log('end');
});
socket.on('error', function() {
console.log('error');
});
To be honest, I thought the error event could do it. Is there any other events I'm actually missing?
I found it. It was abvious:
socket.on('close', function() {
//Do something
});
Related
currently I am using the following code in node.js with socket.io to connect to my server, which is working fine. But if my node.js server is not running, the client is trying to connect to it again and again in intervals - but I would like to stop it and close the socket on the client side if the server is not reachable. I have tried using connect_failed, but unfortunately this is never being called. how can this be done?
function findOpponent(gamemode)
{
console.log('Registering myself on nodejs Server and waiting for 2nd player');
socket = io.connect("http://gladiator.localhost:3000" , {
'query': '&uuid='+uuid+'&authkey='+auth_key+'&gamemode='+gamemode
});
socket.on('connect_failed', function() {
// --> this is never being called
console.log("Sorry, there seems to be an issue with the connection!");
});
socket.on('user join',function(msg){
alert('USER JOINED');
});
socket.on('user leave',function(msg){
console.log(msg);
alert('USER LEFT');
});
socket.on('message',function(msg){
alert(msg);
});
socket.on('gamestart',function(data){
console.log('gamestart');
alert(data.msg);
});
}
try autoConnect and reconnection options for socket io client
{ autoConnect: false, reconnection: false}
EDIT:
and you can listen on connect_error event for catch connection error
socket.on("connect_error", callback)
From the server, I want to be able to detect when a client creates new a room or channel. The catch is that the rooms and channels are arbitrary so i don't know what they will be until the user joins/subscribes. Something like this:
Server:
io.on('created', function (room) {
console.log(room); //prints "party-channel-123"
});
Client:
socket.on('party-channel-123', function (data) {
console.log(data)
})
I also can't have any special client requirements such as sending a message when the channel is subscribed as such:
socket.on('party-channel-123', function (data) {
socket.emit('subscribed', 'party-channel-123');
})
Server:
io.sockets.on('connection', function(socket) {
socket.on('createRoom', function(roomName) {
socket.join(roomName);
});
});
Client
var socket = io.connect();
socket.emit('createRoom', 'roomName');
the io object has references to all currently created rooms and can be used as such:
io.sockets.in(room).emit('event', data);
Hope this helps.
PS. I know its emitting the 'createRoom' that you probably don't want but this is how socket.io is used, this is pretty much copy/paste out of the docs. There are tons of examples on the socket.io website and others.
I may be doing something wrong here but I can't get my head around this.
The following does not work:
client
$("#disconnectButton").click(function() {
socket.emit("disconnect");
});
server
socket.on("disconnect", function() {
console.log("this never gets called");
});
Can't I manually call the disconnect event from the client side? Because the following works:
client
$("#disconnectButton").click(function() {
socket.emit("whatever");
});
server
socket.on("whatever", function() {
socket.disconnect();
console.log("this gets called and disconnects the client");
});
'disconnect' event is Socket.io event,if you use emit to call the 'disconnect',may be cause other problom
so:
$("#disconnectButton").click(function() {
socket.emit("disconnect");
});
replace:
$("#disconnectButton").click(function() {
socket.disconnect();
});
For now, socket.emit('disconnect') or socket.disconnect() doesn't work.
The correct syntax to disconnect to the socket server is
socket.close()
I am trying to develop a simple socket io based chat app using sails MVC.
whenever a client connected socket emitting multiple times(equa to number of clients).
here is my code.
Server :
io=req.socket.manager;
var users=[];
io.sockets.on('connection', function(client) {
console.log("connected");
users.push(client.id);
client.on("chat", function(data) {
io.sockets.sockets[data.to].emit("chat", { from: client.id, to: data.to, msg: data.msg });
client.emit("chat", { from: client.id, to: data.to, msg: data.msg });
});
});
Client :
var socket=new io.connect('http://localhost:1337/');
socket.request('/Chat/index');
socket.emit('connection',function(data){
console.log(data);
});
socket.on('connect', function() {
console.log("Connected.");
//
});
socket.on('chat', function(data) {
console.log(data.msg );
});
please help me , is there any way to get actual socket object in sails?
I am using io=req.socket.manager; which is of req object.
the socket object should be accessible in sails.io on the server side
link
maybe you want to answer to a unique socket id? that can be achieved this way:
In the file sockets.js, at your config folder, find the onConnect property and add code like this:
onConnect: function(session, socket){
sails.io.sockets.socket(socket.id).send('YOUR_EVENT', {'message' : 'your message to a unique socket'});
}
It will send a unique message when a new connection is established. Just a couple of notes:
This can be considered a socket.io issue, not a sails issue, since the method .socket(socket.id) is part of socket.io
This was tested on sails v0.9.8, in other versions the file sockets.js might not be included in the default generated app with sails' new command
This is just an example to show how can it be done, you might need to adapt it to your needs.
Hope this helps.
I'm building a small prototype with node.js and socket.io. Everything is working well, the only issue I'm facing is that my node.js connection will disconnect and I'm forced to refresh the page in order to get the connection up and running again.
Is there a way to reestablish the connection as soon as the disconnect event is fired?
From what I've heard, this is a common issue. So, I'm looking for a best-practice approach to solving this problem :)
Thanks very much,
Dan
EDIT: socket.io now has built-in reconnection support. Use that.
e.g. (these are the defaults):
io.connect('http://localhost', {
'reconnection': true,
'reconnectionDelay': 500,
'reconnectionAttempts': 10
});
This is what I did:
socket.on('disconnect', function () {
console.log('reconnecting...')
socket.connect()
})
socket.on('connect_failed', function () {
console.log('connection failed. reconnecting...')
socket.connect()
})
It seems to work pretty well, though I've only tested it on the websocket transport.
edit: Socket.io has builtin-support now
When I used socket.io the disconnect did not happen(only when i closed the server manually). But you could just reconnect after say for example 10 seconds on failure or something on disconnect event.
socket.on('disconnect', function(){
// reconnect
});
I came up with the following implementation:
client-side javascript
var connected = false;
const RETRY_INTERVAL = 10000;
var timeout;
socket.on('connect', function() {
connected = true;
clearTimeout(timeout);
socket.send({'subscribe': 'schaftenaar'});
content.html("<b>Connected to server.</b>");
});
socket.on('disconnect', function() {
connected = false;
console.log('disconnected');
content.html("<b>Disconnected! Trying to automatically to reconnect in " +
RETRY_INTERVAL/1000 + " seconds.</b>");
retryConnectOnFailure(RETRY_INTERVAL);
});
var retryConnectOnFailure = function(retryInMilliseconds) {
setTimeout(function() {
if (!connected) {
$.get('/ping', function(data) {
connected = true;
window.location.href = unescape(window.location.pathname);
});
retryConnectOnFailure(retryInMilliseconds);
}
}, retryInMilliseconds);
}
// start connection
socket.connect();
retryConnectOnFailure(RETRY_INTERVAL);
serverside(node.js):
// express route to ping server.
app.get('/ping', function(req, res) {
res.send('pong');
});
Start reconnecting even if the first attempt fails
If the first connection attempt fails, socket.io 0.9.16 doesn't try to reconnect for some reason. This is how I worked around that.
//if this fails, socket.io gives up
var socket = io.connect();
//tell socket.io to never give up :)
socket.on('error', function(){
socket.socket.reconnect();
});
I know this has an accepted answer, but I searched forever to find what I was looking for and thought this may help out others.
If you want to let your client attempt to reconnect for infinity (I needed this for a project where few clients would be connected, but I needed them to always reconnect if I took the server down).
var max_socket_reconnects = 6;
var socket = io.connect('http://foo.bar',{
'max reconnection attempts' : max_socket_reconnects
});
socket.on("reconnecting", function(delay, attempt) {
if (attempt === max_socket_reconnects) {
setTimeout(function(){ socket.socket.reconnect(); }, 5000);
return console.log("Failed to reconnect. Lets try that again in 5 seconds.");
}
});