Python, recreate a socket and automatically reconnect
Asked Answered
P

2

8

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

Pyatt answered 8/4, 2013 at 3:2 Comment(1)
what code do you have?Bailes
C
9

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://mcmap.net/q/1468332/-python-check-if-irc-connection-is-lost-ping-pong

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()
Colston answered 26/6, 2013 at 6:19 Comment(1)
would this not only work if there was a continuous stream of data to receive? Seems like it would just reconnect the moment it received an empty packet from the server?Misvalue
J
0

This is the code for Re-Connect socket

import socket
import time

username = "Manivannan"
host = socket.gethostname()    
port = 12345                   # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connected = False
print("Server not connected")
while True:
  if(not connected):
    try:
        s.connect((host, port))
        print("Server connected")
        connected = True
    except:
        pass
  else:
    try:
        s.sendall(username.encode('utf-8'))
    except:
        print("Server not connected")
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        connected = False
        pass
    time.sleep(5)
s.close()
Jupiter answered 28/11, 2018 at 6:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.