Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

python - 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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming this is a connection oriented socket:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...