繁体   English   中英

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

[英]Python : Check if IRC connection is lost (PING PONG?)

所以我的问题是,如果有PING,并且在一分钟的间隔内没有ping,我如何让我的漫游器监听,它会做出反应,好像连接已丢失。 人们将如何去做呢?

编辑:

这是用于注册连接辐射的工作代码(尽管在重新连接时遇到麻烦):

#!/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)
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”。 然后您发送了错误的PONG ...

而是尝试这样的事情:

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

重新连接时遇到问题的原因是,一旦执行此操作,就不会再有循环来侦听传入的数据,并且很可能会ping超时。 连接while循环应如下所示:

while connected:
    try:
        ...
    except socket.timeout:
        global connected
        connected = False
        print connected
        connection(HOST, PORT, NICK, IDENT, REALNAME, CHAN)
        continue
print "Out of loop"

现在,当连接超时时,您将重新连接并开始侦听传入的数据。

注意:现在,应用程序无法终止,您必须在命令行中按[Ctrl] + [C]或构造一个“!quit”类型命令以关闭套接字和应用程序...当然先插座。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM