Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Python (http://www.programmingforums.org/forum43.html)
-   -   How do I reconnect a disconnected socket? (http://www.programmingforums.org/showthread.php?t=15501)

terron Mar 28th, 2008 10:13 AM

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
:

Bad File Descriptor
and if I either use shutdown or just go straight to reconnecting I get:
:

Transport endpoint is already connected

This is what I've got right now:
:

  1. #! /usr/bin/env python
  2. import socket, string
  3. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  4. def doconn():
  5.     sock.connect(("localhost", 1234))
  6. def dodiscon():
  7.     sock.close()
  8.     doconn()
  9.  
  10. doconn()
  11.  
  12. while (1):
  13.     buffer = sock.recv(1024)
  14.     if not buffer:
  15.         dodiscon()


What am I doing wrong?

Freaky Chris Mar 28th, 2008 11:17 AM

Re: How do I reconnect a disconnected socket?
 
Hmm well i think you may find it is because when you call socket.close()
your socket becomes blank so to speak.

:

  1. #! /usr/bin/env python
  2. import socket, string
  3.  
  4. def doconn():
  5.     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  6.     sock.connect(("localhost", 1234))
  7. def dodiscon():
  8.     sock.close()
  9.     doconn()
  10.  
  11. doconn()
  12.  
  13. while (1):
  14.     buffer = sock.recv(1024)
  15.     if not buffer:
  16.         dodiscon()


and so by moving the declaration of your socket into your doconn() function everytime you try to connect it re-defines the socket.

I thinks this works anyway plus i've no doubt been talking aload of rubbish but there we go

Chris

Jimbo Mar 29th, 2008 2:39 AM

Re: How do I reconnect a disconnected socket?
 
When you close the socket, it'll be closed. You can reconnect with a new socket, but you can't use the same one. When it's closed, both OSs will terminate the connection.

Freaky Chris Mar 29th, 2008 4:12 AM

Re: How do I reconnect a disconnected socket?
 
Quote:

Originally Posted by Jimbo (Post 143159)
When you close the socket, it'll be closed. You can reconnect with a new socket, but you can't use the same one. When it's closed, both OSs will terminate the connection.

thats what i was trying to say but just couldn't lol thanks Jimbo


All times are GMT -5. The time now is 9:12 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC