jack-all-trades
jack-all-trades

Reputation: 282

How can I reconnect a socket after a broken pipe?

The program connects to a server, and when the connection is closed by the server, if I try to reconnect it says: socket.error: [Errno 9] Bad file descriptor
If I close the socket in the client and then i try to reconnect, it says: socket.error: [Errno 106] Transport endpoint is already connected.


Is there a way to reconnect it after a broken pipe without creating a new socket?

import socket
host = '127.0.0.1'
port = 1337
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def loop():
    try:
        while 1:
            print s.recv(512)
    except socket.error:
        #s.close()?
        connect()
def connect():
    s.connect((host, port))
    loop()
connect()

Upvotes: 9

Views: 18538

Answers (2)

user339024
user339024

Reputation:

If the file descriptor is bad then you will need to release that resource and create a new socket. This will get you a new file descriptor.

If the connection terminated abnormally, you will have to wait for the server to close it's end of the connection before you can reconnect. I would just poll it frequently (but not too frequently) to see if you can reestablish a connection with your new socket.

How often do you get the bad pipe error?

Upvotes: 3

nos
nos

Reputation: 229274

Assuming this is a connection oriented socket:

No. You have to close the old one and create a new socket,

Upvotes: 14

Related Questions