Python,重新创建套接字并自动重新连接 [英] Python, recreate a socket and automatically reconnect

查看:336
本文介绍了Python,重新创建套接字并自动重新连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python编写IRC机器人.

I'm writing a IRC bot in Python.

来源: http://pastebin.com/gBrzMFmA (对pastebin感到抱歉,我不知道如何有效/正确地使用此处的代码标记)

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

当"irc"插槽消失时,我是否还能去检测它是否没电,然后自动重新连接?

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

我已经搜索了一段时间,发现必须创建一个新的套接字.我正在尝试添加诸如True时捕获socket.error之类的东西:但是它似乎只是挂起而不能正确地重新连接..

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..

谢谢您的帮助

推荐答案

在这里回答:尽管问题所有者接受的答案有效,但我更喜欢约翰·莱德贝特的答案,因为它的简单性,所以只问它: https://stackoverflow.com /a/6853352/625919

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

这篇关于Python,重新创建套接字并自动重新连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆