9

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()
gangadhars
2,7467 gold badges45 silver badges73 bronze badges
asked Sep 20, 2011 at 14:10

2 Answers 2

14

Assuming this is a connection oriented socket:

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

answered Sep 20, 2011 at 14:12
Sign up to request clarification or add additional context in comments.

1 Comment

The reason for this is that a socket connection is managed at the operating-system level (and, this goes for any programming language). Under Linux, a file descriptor is allocated for the connection which is destroyed when the connection is closed, so you need to reconnect which creates a new file descriptor.
3

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?

answered Sep 20, 2011 at 14:14

1 Comment

I get the error when i close the connection in the server. What im wondering if is there a way to recconect to the server with the same socket.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.