0

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.

1 Answers1

0

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 } );
}
jko
  • 2,068
  • 13
  • 25