我一直在尝试使用TCPClient在C#中编写IRC bot。它连接并开始接收命令,使用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);
}
}
答案 0 :(得分:0)
我发现问题不在TCPClient的实际读数中。问题是我的ISP在频道停用30分钟后关闭了连接。因为IRC乒乓是从互联网到(机器人)用户的连续请求 - 回复。我的ISP可能会将此类请求 - 回复活动视为潜在的僵尸网络并关闭连接。
为了防止这种情况,我改变了我的机器人每分钟将PING发送到服务器。随着这种变化,机器人已经稳定整整一周(24/7)。