Python:套接字连接仍然打开

时间:2013-04-20 17:13:39

标签: python sockets bots irc

我在这里已经阅读了一些关于这个主题的问题,但我无法得到一个简单的答案。 我会提供一些代码,以便更容易。

import socket

irc = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )

irc.connect((network, port))

# Do the rest of the connection (set nick, user, join chan)
# Okay, now we're connected

while True:

    doAllTheBotStuff()

我有!quit命令打破了while True:循环。但有时我会因为ping超时或我的网络崩溃等其他原因而被取消。我想做的是:

while True:

    doAllTheBotStuff()

    if not stillConnected():
        break 

我该怎样做stillConnected()功能?


读/写:

我为我的机器人制作了一个课程,但希望你能在没有所有信息的情况下理解它

# READING 

ready = select.select([self.irc], [], [], 1)
if ready[0]:
    temp = self.irc.recv(4096)
    # Here I handle the reading. Parse commands and all that stuff.   

写作始终是对所读内容的回应。我用这个函数:

def send_irc_cmd(self, cmd, args):
    self.irc.send(cmd+" :"+args+"\r\n")

1 个答案:

答案 0 :(得分:1)

认为你需要做的就是在行之后添加一些内容......

temp = self.irc.recv(4096)

...检查temp是否为空字符串,表示远程主机已关闭连接,并使用它来摆脱循环。

我无法更准确或更具体,因为您的代码示例不完整,和/或实际代码的简化。

相关问题