How do I reconnect a disconnected socket?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • terron
    New Member
    • Mar 2008
    • 1

    How do I reconnect a disconnected socket?

    I'm trying to make something that once it is disconnected will automatically try to reconnect. I'll add some more features in later so it doesn't hammer the server but right now I just want to keep it simple and get that part working. The problem is that when I use sock.close I get an error message of
    Code:
    Bad File Descriptor
    and if I either use shutdown or just go straight to reconnecting I get:
    Code:
    Transport endpoint is already connected
    This is what I've got right now:
    Code:
    #! /usr/bin/env python
    import socket, string
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    def doconn():
        sock.connect(("localhost", 1234))
    def dodiscon():
        sock.close()
        doconn()
    
    doconn()
    
    while (1):
        buffer = sock.recv(1024)
        if not buffer:
            dodiscon()
    What am I doing wrong?
  • Subsciber123
    New Member
    • Nov 2006
    • 87

    #2
    Originally posted by terron
    I'm trying to make something that once it is disconnected will automatically try to reconnect. I'll add some more features in later so it doesn't hammer the server but right now I just want to keep it simple and get that part working. The problem is that when I use sock.close I get an error message of
    Code:
    Bad File Descriptor
    and if I either use shutdown or just go straight to reconnecting I get:
    Code:
    Transport endpoint is already connected
    This is what I've got right now:
    [code=python]
    #! /usr/bin/env python
    import socket, string
    sock = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
    def doconn():
    sock.connect((" localhost", 1234))
    def dodiscon():
    sock.close()
    doconn()

    doconn()

    while (1):
    buffer = sock.recv(1024)
    if not buffer:
    dodiscon()
    [/code]

    What am I doing wrong?
    You already closed sock. Now you cannot reuse it. You must create another socket. Here, I think that this should work:

    [code=python]
    #! /usr/bin/env python
    import socket, string
    def doconn():
    sock = socket.socket() # this assumes what you stated explicitly before, as they are the default values
    sock.connect((" ", 1234)) # you don't have to state "localhost" , an empty string will do
    return sock
    def dorecon(sock):
    sock.close()
    return doconn()

    sock=doconn()

    while 1: # grrr! this is not lisp! try not to use parens!
    buffer = sock.recv(1024)
    if not buffer:
    sock=dorecon(so ck)
    [/code]

    I also renamed the second function name so that it made more sense.
    btw: not that there is anything wrong with lisp, just python is not it.
    Also, use [ code=python ] [ /code ] (without spaces) in order to get syntax highlighting

    Comment

    Working...