I have developed one chat application using socket and node js , in start it works perfectly but i have observed that after some interval of time there is one polling error thrown and than socket disconnects.
Error screenshot : https://drive.google.com/file/d/1RWAoqHmpRSR1RkNvE1-XsFtVIvBX24bY/view?usp=sharing
This might fix the issue:
Add this line on server.js:
io.set('transports', ['websocket']);
Add this on client.js:
var socket = io('/',{transports: ['websocket'],upgrade:false});
And do one more thing just use lower socket.io version like 2.0.3
Related
So, I am still in the experimental phase of Socket.io, but I just can't figure out why my code is doing this. So, I have the code below and when I console.log the code, it repeats the the connection even when there is only one connection. Do you know a solution?
io.on('connnection', (socket) => {
console.log("A new user is connected.")
})
Client side:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io()
</script>
Node.js Console:
A new user is connected.
A new user is connected.
A new user is connected.
A new user is connected.
A new user is connected.
A new user is connected.
A new user is connected.
...
(Note: there is only one connection, and I have already cleared the browser cashe)
Here are some of the possible reasons for socket.io connecting over and over:
Your socket.io client and server versions do not match and this causes a connection failure and an immediate retry.
You are running with some infrastructure (like a proxy or load balancer) that is not configured properly to allow lasting webSocket connections.
You are running a clustered server without sticky webSocket connections.
You have put the server-side io.on('connnection', ...) code inside some other function that is called more than once causing you to register multiple event handlers for the same event so you think you're getting multiple events, but actually you just have multiple listeners for the one occurrence of the event.
Your client code is calling its var socket = io() more than once.
Your client page is reloading (and thus restarting the connection on each reload) either because of a form post or for some other reason.
FYI, you can sometimes learn something useful by installing listeners for all the possible error-related events on both client and server connections and then logging which ones occur and any parameters that they offer. You can see all the client-related error events you can listen to and log here.
To solve repetion problem write your code like that for socket:
io.off("connnection").on('connnection', (socket) => {
console.log("A new user is connected.")
})
I have developed an application with ReactJS, ExpressJS, MongoDB and SocketIO.
I have two servers:- Server A || Server B
Socket Server is hosted on the Server A and application is hosted on the Server B
I am using Server A socket on Server B as a client.
Mainly work of Server A socket is to emit the data after fetching from the MongoDB database of Server A
Everything is working as expected but after 4-5-6 hours stop emitting the data but the socket connection will work.
I have checked using
socket.on('connection',function(){
console.log("Connected")
)
I am not getting whats the wrong with the code.
My code : https://jsfiddle.net/ymqxo31d/
Can anyone help me out on this
I have some programming errors.
I am getting data from MongoDB inside the setInterval() so after a little while exhausts resources and database connection starts failing every time.
Firstly i have created a Single MongoDB connection and used every place where i needed.
2ndly i removed setInterval and used setTimeout as below. (NOTE: If i continue using setInterval it execute on defined interval. It doesn't have any status that the data is emitted or not [this also cause the heavy resource usages] but i need to emit the data to socket when successfully fetched.)
setTimeout(emitData,1000);
function emitData(){
db.collection.find({}).toArray(function(data){
socket.emit('updateData',data);
setTimeout(emitData,1000);
})
}
My browser is defaulting to "polling" method, causing me not to get the disconnect event on the server side.
I've tried the solution covered in socket.io force a disconnect over XHR-polling but this didn't do the trick for me:
Server.socket = io.connect("https://somedomain:8443", {"sync disconnect on unload":true, secure:true});
How can I track users leaving my server with polling?
so, apparently for some reason the heartbeat timeout was too long for me to think the disconnect mechanism was working.
I changed the timings:
var io = require('socket.io')(server, {'pingInterval': 4000, 'pingTimeout': 8000});
In the server, and after 8 seconds, sure thing, I get the disconnect event.
The low numbers are because I'm creating a multiplayer game...
I'm writing a node.js socket.io websockets application (version 1.3.7 of socket.io), and about 75% of the time the client takes a long time to connect to the server - the other 25% of the time it connects pretty much instantly. I've enabled debugging on both the server and the client, and it hangs in both places at the same spot:
Server Log
Client Log (Chrome)
Eventually it will connect, and I've been able to make it connect faster by reducing the timeout from the default of 20 seconds to about 5 seconds, but I'm not sure why it's hanging in the first place. Watching the Chrome network tab, it seems like when a connect attempt is made it will either work immediately or it won't work for the rest of the connect attempt. So dropping the timeout to 5 seconds just means it will make more attempts faster, one of which will eventually succeed.
Network Log (Chrome)
In this case it took 5 connection tries, about 20 seconds, to connect.
Client Code
// client.wsPath is typically http://127.0.0.1:8080/abc, where abc is the namespace to connect to.
client.socket = io.connect(client.wsPath, {timeout: 5000, transports: ["websocket"]});
Server Code
var express = require("express");
var io = require("socket.io");
var htmlApp = express();
var htmlServer = http.Server(htmlApp);
htmlServer.listen(DISPATCH_SERVER_LISTEN_PORT, function()
{
log.info("HTML Server is listening on port " + DISPATCH_SERVER_LISTEN_PORT);
});
var wsServer = io(htmlServer, {transports: ["websocket"]});
var nsp = wsServer.of("/" + namespace);
nsp.on("connection", function(socket)
{
log.info("connect");
};
We've found that clearing the browser cookies can help, but doesn't seem like a permanent solution - is there something that I'm doing wrong?
We are facing similar issue with socket IO SDK. It seems the SDK is actually waiting for the acknowledgement(util is receives the message with SID) to start messaging. But in the typical WS/WSS communication we can start messaging immediately after the connect. We are trying to tweak the SDK in such a way that it can start messaging immediately after connection establishment. Please share if any one has found a better approach.
Anybody else still facing this error?
It is happening to a server I deployed, these are the versions:
"socket.io-client": "^4.5.1"
"socket.io": "^4.5.1"
Sometimes it connects instantly, but others it takes around 1~2 minutes
I've ran into a fairly difficult to debug error with my node web server.
Background
I'm creating a node server with socket.io to provide a restful service, connected to mongodb which use web sockets(socket.io) for server-client messages.
Issue
In my node app, I've used an npm package called node-scheduler, in which I do some processing at set times(these are very dynamic times but work fairly well to date).
So I'll set off a job, using node-scheduler and when it ends you can provide a function.
In this function I emit a web socket message, exactly how I emit messages in the rest of the application but my client side never receives the message.
Checking the logs the client disconnections then re connections after the function has completed.
I've debugged a little further, and I send two messages to the client in this function. Only one of them is processed by the client. May be a client issue not a server issue.
Any ideas for solutions or suggestions would greatly be appreciated.
Well generally socket.io is only meant to be used as a "channel". You should have the Client exist as a separate entity in memory or something, and update the socket if and when it reconnects. Otherwise you're just sending to the past (disconnected) sockets.
Using passport you can identify a client as a user.
app.get('/', function(req, res){
// req.user;
});
Using passport.socketio you can get the same user in your socket
io.on('connection', function(socket){
// socket.request.user;
socket.request.user.socket = socket;
// this will be updated with the latest socket in case of a future reconnection
// So now you can be sure that user object will always have the latest socket
nodeScheduler(function(){
carryOutJobs(function callback(){
socket.request.user.socket.emit('done');
// will always emit to the "latest" socket.
});
});
});