0

I am trying to implement a TCP server which will not hang (potentially) forever during a recv or sendall operation.

I thought it would be enough to specify a timeout for the active socket, but this seems not to be the case: see here

So, how could I extend my code to ensure that:

  • recv will not hang up in any case
  • sendall will not hang up in any cases (well, I am not sure if sendall can hang up at all)

Any suggestions are highly appreciated.

Rickson
  • 1,040
  • 2
  • 16
  • 40

1 Answers1

1

What you need is the select function. It takes 3 arguments; read list, write list, error list. And then it returns three values, each being a list of the socket that you inputted that are ready to be either be written to, read from. ( Or has had an error if you wanted to check for that. )

rl , wl , el = select( [ serversocket , clientsocket ] , [] , [] );
for e in rl:
  if e == serversocket:
    acceptConnection( serversocket );
  else:
    readFromClient( clientsocket );
NullData
  • 394
  • 2
  • 8
  • Hi! Thank you for you answer. Does this this also take care that sendall will not hang up? Do I not need to make the active socket non-blocking? – Rickson Jul 14 '13 at 18:01
  • You want to go into non blocking mode for `sendall`, but before you write to it next time, make sure to check if you can write to it yet with `select`. – NullData Jul 14 '13 at 18:09
  • You do not need to make the socket nonblocking. Select tells zou if something is there and then you can start to read/write – User Jul 14 '13 at 18:09
  • The reason you want to go into non-blocking mode is so that you don't have to wait for large chunks of data being sent before moving on in the program flow. – NullData Jul 14 '13 at 18:10
  • However, when using select, do I have issues with the server getting stucked if the client crashes, and doesn't shut down the socket properly? If the crash happend after the select operation... – Rickson Jul 14 '13 at 18:45
  • You just need to catch any exception coming your way, and then disconnect the client. – NullData Jul 14 '13 at 19:03
  • Thanks a lot for clarifying this. But where is the best place to insert your code? In the final while loop or within handler? – Rickson Jul 14 '13 at 19:13