Andrius
Andrius

Reputation: 653

There is no timeout exception in socket

I am very confused about sockets... I have two scripts, one is server.py, and second is client.py:

server.py

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 1235))
server.listen(1)

while True:
    client, address = server.accept()

    try:
        client.recv(1024)
    except socket.Timeouterror:
        print 'timeout'

client.py

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('ip', 1235))

Why server.py script does not show an error of timeout?

Upvotes: 1

Views: 691

Answers (2)

Manoj Pandey
Manoj Pandey

Reputation: 4666

Some of the socket calls are blocking, by default. If nothing happens, they would block indefinitely. recv() is one of those calls. Other blocking calls are accept(), recvfrom(), read().

Upvotes: 2

mata
mata

Reputation: 69012

You need to set the timeout for the socket if you wan to have one:

...
client, address = server.accept()
client.settimeout(10)
...

Or you can use a default timeout for all sockets.

socket.Timeouterror doesn't exist, it should be socket.timeout.

Also, you probably should close the client socket, otherwise the client will not know that the connection is closed. The timeout alone doesn't do that for you.

Upvotes: 3

Related Questions