2

I'm using a python socket as a file to talk to another process:

def connect(self):
    try:
        self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect( (self.target, self.port) )
        self.fobj = self.sock.makefile()

Normally I'd write a command through the socket and expect a reply within a certain period. So my question is: is there a way to achieve timeout when reading a line from the socket file object?

Thanks,

2
  • Have you tried to use settimeout()? Commented Aug 2, 2011 at 15:09
  • what do you mean exactly by saying way to achieve timeout, are you asking for capturing exception? Commented Aug 2, 2011 at 15:13

1 Answer 1

2

Taken from Python's documentation about socket.makefile():

socket.makefile([mode[, bufsize]])

Return a file object associated with the socket. (File objects are described in File Objects.) The file object references a dup()ped version of the socket file descriptor, so the file object and socket object may be closed or garbage-collected independently. The socket must be in blocking mode (it can not have a timeout). The optional mode and bufsize arguments are interpreted the same way as by the built-in file() function.

Therefore you can't have a timeout on a socket-file, if you need timeouts, you must use regular sockets.

Sign up to request clarification or add additional context in comments.

4 Comments

Although the documentation says so, it is actually possible and reliable to use timeouts. This was tested on linux and windows with python 2.7.14
@NameOfTheRose do you have any reference to backup your claim?
@eric, sorry for the delayed response. What do you mean by reference? I have a working program that does that. If you are still interested I will try to post a minimum program demonstrating it.
you claim it's reliable, is it documented anywhere? By reference I mean documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.