Python:检查IRC连接是否丢失(PING-PONG?)

2024-06-26 17:55:07 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我的问题是,如果有PING,如果在一分钟的间隔内没有PING,我如何让我的bot监听,它会像断开连接一样做出反应。你怎么能这样做呢?

编辑:

这是用于注册连接影响的工作代码(尽管在重新连接时遇到问题):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import socket
import string
import os
import platform
import time

# Variables
HOST = "irc.channel.net"
PORT = 6667
NICK = "Botname"
IDENT = "Botname"
REALNAME = os.getenv('USER')
CHAN = "##ChannelName"
readbuffer = ""

# Our IRC connection
irc = socket.socket()
irc.settimeout(300)
connected = False
def connection(host, port, nick, ident, realname, chan):
    while connected is False:
        try:
            irc.connect((host, port))
            irc.send("NICK %s\r\n" % nick)
            irc.send("USER %s %s bla :%s\r\n" % (ident, host, realname))
            irc.send("JOIN :%s\r\n" % chan)
            # Initial msg to send when bot connects
            irc.send("PRIVMSG %s :%s\r\n" % (chan, "TehBot: "+ nick + " Realname: " + realname + " ."))
            global connected
            connected = True
        except socket.error:
            print "Attempting to connect..."
            time.sleep(5)
            continue
connection(HOST, PORT, NICK, IDENT, REALNAME, CHAN)

while connected:
    try:
        data = irc.recv ( 4096 )
        # If connection is lost
        if len(data) == 0:
            break
        print data
        # If Nick is in use
        if data.find ( "Nickname is already in use" ) != -1:
            NICK = NICK + str(time.time())
            connection(HOST, PORT, NICK, IDENT, REALNAME, CHAN)
        # Ping Pong so we don't get disconnected
        if data[0:4] == "PING":
            irc.send ( "PONG " + data.split() [ 1 ] + "\r\n" )
    except socket.timeout:
        global connected
        connected = False
        print connected
        break
print "Out of loop"
connection(HOST, PORT, NICK, IDENT, REALNAME, CHAN)

Tags: importsendhostdatatimeisportirc
3条回答
last_ping = time.time()
threshold = 5 * 60 # five minutes, make this whatever you want
while connected:
    data = irc.recv ( 4096 )
    # If Nick is in use
    if data.find ( 'Nickname is already in use' ) != -1:
        NICK = NICK + str(time.time())
        Connection()
    # Ping Pong so we don't get disconnected
    if data.find ( 'PING' ) != -1:
        irc.send ( 'PONG ' + data.split() [ 1 ] + '\r\n' )
        last_ping = time.time()
    if (time.time() - last_ping) > threshold:
        break

这将记录每次得到ping的时间,如果没有ping的时间太长,则中断connected循环。你不需要while connected == True:,只要while connected:做同样的事情。

另外,考虑使用connection而不是Connection,Python约定只对类使用大写名称。

只要你的连接还在,就没有理由做任何花哨的“超时”把戏。如果从recv返回的数据长度为0,则TCP连接已关闭。

data = irc.recv(4096)
if len(data) == 0:
    # connection closed
    pass

我怀疑如果连接没有完全终止,recv()也会抛出异常。

编辑:

我不知道你想做什么。IRC服务器偶尔会发送一个PING。如果您没有用PONG响应,那么服务器将断开您的连接。当服务器断开连接时,您的recv()调用将返回一个0长度的字符串。

您所要做的就是在获得连接时对PING做出响应,并处理连接是否碰巧关闭。

你的逻辑应该是这样的:

keep_trying_to_connect = True
while keep_trying_to_connect:
    # try to connect
    irc = socket.socket()
    # send NICK, USER, JOIN here
    # now we're connected and authenticated start your recv() loop
    while True:
        data = irc.recv(4096)
        if len(data) == 0:
            # disconnected, break out of recv loop and try to reconnect
            break
        # otherwise, check what the data was, handling PING, PRIVMSG, etc.

另一件要记住的事情是,在得到\r\n序列之前,您需要缓冲任何接收到的数据,但您不会总是同时得到一条完整的消息;您可能会得到一行、三行或三行半。

您不应该使用data.find('PING'),因为它在其他消息中也会找到“PING”。然后你发了一个错误的乒乓球。。。

相反,试试这样的方法:

if data[0:4] == "PING":
    irc.send("PONG " + data.split()[1] + "\n")

相关问题 更多 >