繁体   English   中英

30-40分钟后,.NET IRC TCPClient读取挂起

[英].NET IRC TCPClient read hang after 30-40 minutes

我一直在尝试使用TCPClient在C#中编写IRC机器人。 它连接并开始接收命令,并以PONG命令响应PING命令。 就这样。

但是,由于某种原因,它会在30至40分钟后挂起,以读取下一行数据。 我已经使用Wireshark检查了PING和PONG消息,它们对我来说看起来不错。 服务器也接收到PONG,因为我确实在Wireshark中看到我的计算机正在接收ACK数据包。

奇怪的是,在30到40分钟内,它绝对可以正常工作。 我怀疑我在StreamReader上做错了什么,但是在网上搜索了几天后,我陷入了困境。

有人会喜欢我的代码吗? 非常感谢。

public class Bot
{
    private NetworkStream ns;
    private StreamReader reader;
    private StreamWriter writer;
    private Encoding enc;           // The encoding used.

    /// <summary>
    /// Initialize the bot.
    /// </summary>
    public Bot()
    {
        enc = new UTF8Encoding();
    }

    /// <summary>
    /// Connects the an IRC server.
    /// </summary>
    /// <param name="url">The url of the server.</param>
    /// <param name="port">The port to connect to.</param>
    /// <param name="user">The username to use.</param>
    /// <param name="nick">The nick to use.</param>
    /// <param name="realName">The users real name.</param>
    public void Connect(string url, ushort port, string user, string nick, string realName)
    {
        TcpClient client = new TcpClient();

        try
        {
            client.Connect(url, port);
        }
        catch (Exception ex)
        {
            throw new Exception("Could not connect to endpoint.", ex);
        }

        ns = client.GetStream();
        reader = new StreamReader(ns, enc);
        writer = new StreamWriter(ns, enc);
        writer.AutoFlush = true;

        Send("USER " + user + " 0 * :" + realName + "\r\n");
        Send("NICK " + nick + "\r\n");
    }

    /// <summary>
    /// Processes a command.
    /// </summary>
    /// <param name="command">The command to process.</param>
    public virtual void ProcessCommand(IRCCommand command)
    {
        if(command.Command == "PING")
        {
            Send("PONG :" + command.Parameters[0] + "\r\n");
        }
    }

    /// <summary>
    /// Receives and processes a command.
    /// </summary>
    public void ReceiveAndProcess()
    {
        string line = reader.ReadLine();

        if (!string.IsNullOrEmpty(line))
        {
            Console.WriteLine("raw : " + line);

            IRCCommand cmd = new IRCCommand();
            cmd.Parse(line);

            ProcessCommand(cmd);
        }
    }

    /// <summary>
    /// Sends a command to the irc server.
    /// </summary>
    /// <param name="ircCommand">The command to send.</param>
    protected void Send(string ircCommand)
    {
        Console.Write("sent: " + ircCommand);
        writer.Write(ircCommand);
    }
}

我发现问题不在实际从TCPClient中读取。 问题是我的ISP在通道中闲置30分钟后关闭了连接。 由于IRC乒乓是从Internet到(bot)用户的连续请求答复。 我的ISP可能将这种请求-答复活动视为潜在的僵尸网络,并关闭了连接。

为了防止这种情况,我更改了漫游器以每分钟将PING发送到服务器。 有了此更改后,该漫游器已经稳定了整整一周(24/7)。

暂无
暂无

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

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