[英].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.