Python, recreate a socket and automatically reconnect

巧了我就是萌 提交于 2019-12-03 14:30:50
DharmaTurtle

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()

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()
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!