socket.io - .on not working on client side - node.js

I have some very basic code that uses socket.io
Client
var socket = io();
// Do some stuff...
socket.emit('hello', 'please like me');
// Wait for a response
socket.on('hello back!', function(msg) {
console.log('Yay, he replied:', msg);
});
Server
var app = require('express');
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket) {
console.log('a user connected');
socket.on('disconnect', function() {
console.log('user disconnected');
});
socket.on('hello', function() {
// Code to decide wether or not I like the client
// ...
// I do like the client!
socket.emit('hello back!', 'how are you');
console.log('I said hello back!');
});
});
Hopefully you managed to get the picture. So ideally, this would happen:
Client connects
After a while, client emits hello
Server sees this, emits hello back!
Client notices the hello back! event
Everyone is happy!
But this isn't the case for me unfortunately. Instead, steps 1-3 work perfectly. But when you reach step 4 and 5, things start to fall apart. Client never logs anything after hello back! event is emitted.
This is not my full code, I figured it would make it easier for you to understand it. It's very possible that I've made some silly mistake somewhere, maybe without including it in this code. But please let me know if there is anything fundamentally wrong with what I am doing.
Cheers

This is a few years old, but in case anyone stumbles across this in the future:
My problem had nothing to do with my code shown above. Instead, it was a configuration error.
I was hosting my project on glitch.com who state that they support websockets, but the error was caused because the server was not able to get across to the client (client never received any data from server at all after websocket connection was opened).
This was an error that I had in 2018 with glitch.com, and I know that other people have had it too. It also seemed to be related somehow to websockets connecting via a domain name and with SSL, but I can't recall the exact circumstances.

Related

Socket.io send notification only to request initiator?

First of all I'm an OG bare metal Java server side guy. That means I'm new to Docker, Node.js (JavaScript in general), socket.io and trying to learn all these things at once so please pardon me if I've made an obvious mistake. I've been working on a pro-bono project for some time in hope that in exchange I get to learn all of these things and move into the new way of doing things.
Now, having said that, moving along to my question - In the code snippet below (especially the last line)
io.on('connection', function (socket) {
console.log(`connection made from ${socket.id}`);
socket.on('disconnect', function () {
console.log(`connection ${socket.id} closed`);
});
socket.on(DOWNSTREAM_MESSAGE, function (msg) {
//console.log(`Received socket payload: ${msg} from ${socket.id}`);
iopubClient.publish(DOWNSTREAM_MESSAGE, msg);
});
iosubClient.subscribe(UPSTREAM_MESSAGE, message => {
//console.log(`Sending socket payload: ${message} to ${socket.id}`);
socket.emit(UPSTREAM_MESSAGE, message);
});
});
as far as I understand from all the internet sleuthing is that:
io.emit(....
broadcasts to all clients the server socket is connected to, and
socket.emit(....
sends to the call initiator (specifically referring to emit cheat sheet among other sources).
However, with the code snippet above, even when I'm using socket.emit, all subscribing socket.io clients receive the message as if it were a broadcast which isn't what I want. I really do want to send the response back to the io that initiated this particular request.
I've tried almost every way of achieving session stickiness from session stickiness (current implementation an attempt via cookie based stickiness with a HAProxy in front of the service).
In case it helps you help me, full code-base is here.
As I mentioned, I'm learning all of this on the fly so I will not be embarrassed (in fact would be quite thankful!) if you point me to something I'm doing wrong, but for the life of me, I cannot get the response to go only to the request initiator.
Please help?!

Socket.IO: connection to a non-existing namespace

First post, i'll try to be as clear as possible :)
I'm trying to create on Demand namespaces on my SocketIO/NodeJS App.
Basically, the server create a specific namespace for each client.
I need to handle, server side, the case where the client try accessing a non-existing namespace.
The idea is to avoid any unwanted connection server-side, or at least, handle it to force the disconnection.
But while testing, it seems that when i try this, on client Side :
var socket = io("thisNameSpaceDontExist");
socket.on('connect', function(){
window.console.log('connected to server');
})
The 'connect' event won't trigger, which seems perfect !
Doing a console.log on socket, it displays this:
connected: false
disconnected: true
But the main problem, is that, Server Side, it's different, there is an active connection...
While doing some research, i found this issue https://github.com/Automattic/socket.io/issues/1867, still, i'm on the last version at this time: 1.3.5
for information, the socketIOHandler code i'm using:
io.on('connection', function (socket) {
console.log("[SocketIOHandler::Connection] +1");
socket.on('disconnect', function () {
console.log("[SocketIOHandler::Disconnection] -1");
});
});
PS:
Also find some issues and MR claiming the support of dynamic namespaces: https://github.com/Automattic/socket.io/issues/1854, but these are not merged, so i don't really understand the behavior on my code...
Thank you!

emitting data via socket on browser close /window close

I need to send data to nodejs server via socket.io when the user closes the browser tab .
I tried doing :
var data={};
window.onbeforeunload = function() {
// i have a object to be sent
data.data1='abcd';
data.data2=1234;
socket.emit("senddata",data);
}
This code works when the user navigates around clicking links on the site but doesnot work when the user closes the browser tab
I also tried configuring the socket io on server side as below .. thinking the error may be due to socket connection being closed before emitting data:
var io = require('socket.io').listen(app.listen(port));
io.configure(function () {
io.set('close timeout',12000);
});
It also didnt work most of the time.
I also tried this on client side:
var socket = require('socket.io').listen(80, {
"sync disconnect on unload":false
});
It also did not work
I had tried receiving data like this
var io = require('socket.io').listen(app.listen(port));
io.sockets.on('connection', function (socket) {
socket.on('senddata', function (data) {
// data processing
});
});
please ..help me with this problem..thanks in advance..
When user connects - register on server side the time it happened.
Socket.IO has heart beating and pinging functionality. So just subscribe to disconnect event on server side and once it happens - means client disconnected - and you have on server time when client had connection. So that way you have timespan of client session.
Do not trust client to tell you any time or important data, as client can simply 'lie' - which leads to hacks/cheats/bugs on your server-side.
There is no reliable way to send data just before disconnect from client-side at all. There is nothing in Socket.IO for that, nor in just one of transports (WebSockets). As well as there is too many different scenarios of disconnection (power off, force close, ethernet cable out, wifi lose, etc).

Socket.IO is not triggering the connect event

I'm trying to setup a Socket.IO server, and right now, connecting doesn't seem to be working the way it does in the Wiki. I'm connecting to a server using the namespace /client, and I'm successfully seeing the connection made in the debug log, but the connection message is never display (and the other contents are never getting attached).
Server-side
var clients = io
.of('/client')
.on('connect', function (socket) {
// This is never getting run
console.log('Client connected');
});
Client side
var socket = io.connect('http://localhost:8082/client');
Why, in the above code, am I not getting the 'Client connected' message in my console?
So, turns out this is a very simple issue, as I suspected. The client uses the connect event, but the server uses connection.
The code should look like:
var clients = io
.of('/client')
.on('connection', function (socket) {
// This is never getting run
console.log('Client connected');
});

socket.io - works first time, not second time onwards

When I start my node.js server and client gets connected, I am able to send a request from client (socket.emit) and get a response (socket.on('rentsAround'....)). But when I connect 2nd time onwards, the client is able to send, but server can not send or emit. So I have to restart the server again. I understand that it is working as expected, but somehow my understanding is wrong somewhere... Would someone please point out.
client side:
========
var socket = new io.Socket();
socket = io.connect();
socket.on('rentsAround', function(data){
registration.handleRentsAround(data);
});
socket.on('locationDetailsRes', function(data){
registration.handleRentsAround(data);
});
socket.on('connect', function(data){
alert('inside connect on client side');
});
socket.on('disconnect', function(){
// do something, if you want to.
});
.............
socket.emit("searchRent", {"lat":lat, "lng":lng});
server side:
========
socket.sockets.on('connection', function(client){
client.on('searchRent', function(msg){
console.log('inside on connection');
// do something and reply back
client.emit('rentsAround',{"totalRents":docs.length, "rents":docs});
});
client.on('disconnect', function(){
sys.puts("client disconnect");
mongoose.disconnect();
});
Socket.io 0.7 onwards will try and reuse connections to the same host. In my experience I've found this behaviour can be a little flakey.
I can't tell from the small code sample you provided, but I suspect the problem is that the second call to connect() is trying to reuse the first (closed) connection.
The workaround is to pass the 'force new connection' option when you call connect(). Eg:
io.connect("http://localhost", {'force new connection': true});
Your second line discards the object created in the first line. Simply doing this should work:
var socket = io.connect();
The problem with first send and second fail could be due to browser/protocol. I have seen such behaviour with Internet Explorer and XHR transport, and also with Opera using JSONP.
If you are using IE, try switching to JSONP and it should work properly. This can be done on the server side, by supplying the transport list to configuration. Just make sure JSONP comes before XHR. Something like this:
sio.set('transports', [
'websocket'
, 'flashsocket'
, 'jsonp-polling'
, 'xhr-polling'
, 'htmlfile'
]);
As of socket.io 1.0, two settings control this behaviour:
"force new connection":true, on the client connect() call.
"cookie":false, on the server Server() constructor.
Apparently, both produce the exact same behaviour.
The second method is, as of today, undocumented. However, looking at the source code you can see that all options passed to socket.io Server() are passed to the internal Engine.io library Server() constructor, which lets you change any of the options there. These options are documented here:
https://github.com/LearnBoost/engine.io

Resources