Python中,重新建立一个插座,并自动重新连接(Python, recreate a socket

2019-08-20 05:29发布

我用Python写一个IRC bot的。

来源: http://pastebin.com/gBrzMFmA (抱歉引擎收录,我不知道如何efficently /正确使用代码tagthing放在这里)

当“IRC”插座死了,反正是有,我可以去检测,如果它死了,然后自动地重新连接?

我是谷歌搜索一段时间了,发现我会创建一个新的插座。 我试图和添加东西,像抓住的,而真正的socket.error:但似乎只是挂,不正确连接..

感谢您提前帮助

Answer 1:

在这里找到答案: Python的:检查是否IRC连接丢失(?乒乓)

虽然问题业主接受的答案的作品,我喜欢这里约翰莱德贝特的回答,索利它的简单: https://stackoverflow.com/a/6853352/625919

所以,对我来说,我沿着线的东西

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


Answer 2:

这是重新连接插座的代码

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


文章来源: Python, recreate a socket and automatically reconnect
标签: python irc