【问题标题】:Python: socket connection still openPython:套接字连接仍然打开
【发布时间】:2013-04-13 22:24:11
【问题描述】:

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

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

【问题讨论】:

  • 当您从套接字读取时,通常会通过 EOF 检测到断开连接,或者如果引发 socket.error。您需要包含执行套接字读取/写入的代码。
  • 我会在问题中加入一部分
  • 已更新,如果您需要任何详细信息,请咨询我 :)

标签: python sockets bots irc


【解决方案1】:

认为你需要做的就是在行后添加一些东西......

temp = self.irc.recv(4096)

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

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

【讨论】:

    猜你喜欢
    • 2014-09-18
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 2015-01-07
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    相关资源
    最近更新 更多