I am using nodejs and socket io. The underlying purpose for the code is to ask for data from the server and to post it on the client website.
I have it made so that every 10 seconds, data is requested from the client to the server, and when the data is received, it shows up on the website.
The problem is that most of the time, receiving data from the server and getting it to the client works, but once in a while, it shuts off and throws an error that says that the socket method emit is undefined. I believe this means that the client is no longer defined.
server code:
sockets[to].emit('cm0101', {soCase : '2', soData : ret } );
this is the code that's getting the TypeError: cannot call method 'emit' of undefined.
What I am confused about is, it works 9 out 10 times, but it fails once in a while (presumably when the client is shut down for whatever reason. But there is no reason/identified cases of the client shutting down)
Did anyone else have the same problem? Does anyone know why this happens? Knowing all possible reasons for this error will help me a lot in trying to find out why this happens.
I assume you did not check sockets[to] before.
You should write your code like this:
var socketTo = sockets[to];
if ( socketTo ) {
sockets[to].emit('cm0101', {soCase : '2', soData : ret } );
}
Related
I am creating a chat application.
In the server, we had an event.
io.emit('userAgentConnectMsg', data);
In the client, we are listening to this event.
socket.on('userAgentConnectMsg', (data) => { console.log(data)} );
Suppose think I have two clients connected to server.
If one client gets message another client will not get that.
This is happening randomly.
I changed code from io.emit to io.sockets.emit still the same issue.
And the worst thing is I am not getting any error either from client or server.
And I am not at all sure where the issue is happening from either it is from server or client.
I did some analysis for socket io before the io.emit
I logged io.sockets.adapter.sids which basically return all connected socket ids.
the issue is sometimes it shows only some sockets and sometimes it shows empty object.
Some can help me if you have faced the same issue.
I have some node.js client side code like this:
socket.emit('clickAccept', { myrecid: recid });
Server side node.js code gets it fine and all is well.
If I take the server down to simulate a server side outage, then click the button that fires this socket.emit on the client side, this happens:
Nothing really, I guess it might eventually time out
When I bring the server back up, the clicks end up being sent to the server and the server acts on them (TCP-like I Guess).
What I want to happen is for those socket.emit calls to die after a short timeout and not send when the server comes back up, it causes all sorts of confusion because if they click 3 times, nothing happens, then when/if the connection or server comes back up they get 3 reactions all at once.
Also, if they click and it times out because the server is down, I would like to show an error to the client user to let them know that basically the click didn't work and to try again.
I know how to act on and show an error if the socket goes down but I don't want to do this if they aren't trying to click something at that time. No sense is firing errors at the user because the socket went down briefly if they have no need to do anything at that moment.
So, to be clear, I only want to show an error if they click on the button and the socket between the client and server is down. AND... If they get an error, I want to kill that emit, not save it all up and fire it and all the other clicks when the server comes back up a few seconds later.
Thanks in advance and I hope that was at least reasonably clear.
The root of your issue is that socket.io attempts to buffer any data that it can't currently send to the server (because the connection to the server is disconnected) and when the server comes back up and the connection is restored, it then sends that data.
You can see the technical details for how this works here: socket.io stop re-emitting event after x seconds/first failed attempt to get a response
You have several implementation options:
If socket.io already knows the client is not connected to the server, then don't buffer the data (perhaps even give you back an error to show to your user).
When socket.io reconnects and there was data buffered while the connection was down, clear that data and throw it away so old data isn't sent on a reconnect.
Implement a timeout to do one of the above after some sort of timeout.
So, to be clear, I only want to show an error if they click on the button and the socket between the client and server is down. AND... If they get an error, I want to kill that emit, not save it all up and fire it and all the other clicks when the server comes back up a few seconds later.
Probably, the simplest way to do that is to implement a version of what is shown in the above referenced answer:
Socket.prototype.emitWhenConnected = function(msg, data) {
if (this.connected) {
this.emit(msg, data);
return null;
} else {
return new Error("not connected");
}
}
Then, switch your code from using .emit() to use .emitWhenConnected() and check the return value when using it. If the return value is null, then no error was detected. If the return value is not null, then there was an error.
Thanks for the other answers and help. I ended up solving this in a super simple way. See below:
if (socket.connected){
// Do your thing here
} else {
// Throw error here that tells the user they're internet is likely down
}
Hope this helps someone out there, it was a huge improvement in our code to make sure that user's are getting proper feedback when if they have brief network/internet outages.
Hi i am having trouble with creating a socket communication from java script code.
I am always getting error while sending a message or closing the socket from server.
My Socket server code.
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
break;
}
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
JavaScript code:
var connection = new WebSocket('ws://Myip:11000', ['soap', 'xmpp']);
// When the connection is open, send some data to the server
connection.onopen = function () {
connection.send('Ping'); // Send the message 'Ping' to the server
connection.send('your message');
};
// Log errors
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
connection.onclose = function (msg) {
console.log('WebSocket Error ' + msg);
};
It gets connected to server socket, but always gets error while closing or sending a message from server.
If this is really your actual code:
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
…then it's pretty broken. First, you can't assume that Socket.Send() actually sends all the bytes you asked it to. You have to check the return value, and keep sending until you've actually sent all the data.
Second, the initiation of a graceful closure should use SocketShutdown.Send, not SocketShutdown.Both. Specifying "Both" means (among other things) that you're not going to wait for the other end to negotiate the graceful closure. That you're just done and won't even receive any more data, in addition to being done sending.
And of course, the code is calling Close() before the other end has in fact acknowledged the graceful closure (by itself sending any remaining data it wanted to send and then shutting down with "Both").
Is all this the reason for your problem? I can't say for sure, since I have no way to test your actual code. But it's certainly a reasonable guess. If you tear down the connection without waiting after you try to send something, there's not any guarantee that the data will ever leave your machine, and in any case the other end could easily see the connection reset before it gets a chance to process any data that was sent to it.
There aren't a huge number of rules when it comes to socket programming, but what rules exist are there for a reason and are generally really important to follow. You should make sure your code is following all the rules.
(The rest of the code is also different from what I'd consider the right way to do things, but the problems aren't entirely fatal, the way that the over-eager connection destruction is).
I am afraid WebSocket does not work that way.
When the Javascript code connects to the server, it will send a HTTP request as ASCII text. That request will include a HTTP header Sec-WebSocket-Protocol: soap, xmpp, as you are requiring those protocols in your WebSocket creation.
Since your server code does not reply with an appropiate HTTP response accepting the websocket connection, the connection will fail. When you try to send data back, the client will not recognize it as a HTTP response and a error will be thrown.
A websocket is not a regular socket connection, it won't work that way. It requires HTTP negotiation and there is a schema for data framing. I recommend you to go through this article that explains very well how it works: http://chimera.labs.oreilly.com/books/1230000000545/ch17.html
If you are interested in learning how to develop a server, take a look to this tutorial in MDN: https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_server I also have an open source WebSocket server in C# you can take a look if you like.
I'm trying to find the definition of connect_timeout, when is it fired, what's the use for it?
Reading here : http://socket.io/docs/client-api/#manager(url:string,-opts:object)
Right now I have an app I tried to run without turning on the server, and it tries to connect and the event "Reconnecting" is fired for 4 attempts, one every 2 seconds. Then it says "Failed Reconnecting" when it hits the 4 attempt mark and fires the event "reconnect_failed".
I haven't been able to hit the connect_timeout event. How do I do that? When does it happen?
I was hoping Socket.IO had some sort of function of "CONNECTING" and then if it failed it would continue attempting "CONNECTING" and if that failed it would say "CONNECTION FAILED" and if it connected successfully at some point, it would then call "RECONNECTING" instead and if that failed after a certain amount of attempts it would say "RECONNECTING FAILED". Is that something that has to be programmed by me? I haven't seen it built in.
Connection timeout is when a client is connected to the server and it takes too long for a response to be received, causing the client to disconnect because it has stopped receiving anything from the server. This can be caused by faulty internet or if the client loses connection to the server (i.e. the clients internet becomes disconnected). This is true for most server based communications and is likely the same for socket.io.
I'm using the cfwebsocket tag in Coldfusion to create a web socket connection.
I looked at an example from here http://www.sagarganatra.com/2012/03/html5-websockets-in-coldfusion-10.html
and near the end it shows you all the javascript calls you can make on the web socket object.
However, when I try to make any call on it I get an error that it is undefined.
For example I have:
<cfwebsocket name="ws" onMessage="messageHandler" onOpen="openHandler" onClose="closeHandler" onError="errorHandler" subscribeTo="chat" />
and in my javascript i call
alert(ws.isConnectionOpen());
and I get the error in firebug: TypeError: ws is undefined.
Anyone know why I can't call it?
My chat works fine and I can connect and chat properly. I just wanted to close the connection when the chat ended so I was looking into how it's done calling the websocket but I don't know why it's not working.
Note that I am using jQuery and the javascript is wrapped in the document ready.
First, you can't interact with the ws object till it establishes a connection to the server.
There are a couple of ways to handle this scenario. You can use the "onOpen" attribute and have it call a function once the web socket connect has been established.
However, you are probably better off just using the "onMessage" attribute and create a generic listener function that processes all web socket messages from the server.
function messageHandler(msg) {
if (msg.type == 'response' && msg.reqType == 'welcome'){
alert('user connected');
}
}