Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, recreate a socket and automatically reconnect

Tags:

python

irc

I'm writing a IRC bot in Python.

Source: http://pastebin.com/gBrzMFmA ( sorry for pastebin, i don't know how to efficently/correctly use the code tagthing on here )

When the "irc" socket dies, is there anyway I could go about detecting if its dead and then automatically reconnecting?

I was googling for awhile now and found that I would have to create a new socket. I was trying and added stuff like catching socket.error in the while True: but it seems to just hang and not reconnect correctly..

Thanks for help in advance

like image 342
Pro Fessor Avatar asked Apr 08 '13 03:04

Pro Fessor


People also ask

How do you reconnect a socket in Python?

A simple solution to this issue is to place the connect() method within a while loop and surround it with a try-except statement. If the connection is successful, then the application will continue with the rest of the script, otherwise it will wait a few seconds and attempt to reconnect again.

What is socket timeout Python?

A new Python socket by default doesn't have a timeout. Its timeout defaults to None. Not setting the connection timeout parameter can result in blocking socket mode. In blocking mode, operations block until complete or the system returns an error.

Can a socket send and receive at the same time Python?

You can send and receive on the same socket at the same time (via multiple threads). But the send and receive may not actually occur simultaneously, since one operation may block the other from starting until it's done.


1 Answers

Answered here: Python : Check if IRC connection is lost (PING PONG?)

While the question owner's accepted answer works, I prefer John Ledbetter's answer here, soley for its simplicity: https://stackoverflow.com/a/6853352/625919

So, for me, I have something along the lines of

def connect():
    global irc
    irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    irc.connect((server, port))
    #and nick, pass, and join stuffs
connect()
while True:
    data = irc.recv(4096)
    if len(data) == 0:
        print "Disconnected!"
        connect()
like image 121
DharmaTurtle Avatar answered Sep 29 '22 11:09

DharmaTurtle