这是我的代码Form1
:
namespace Irc_Bot
{
public partial class Form1 : Form
{
int port;
string buf, nick, owner, server, chan;
System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient();
System.IO.TextReader input;
System.IO.TextWriter output;
public Form1()
{
InitializeComponent();
//Get nick, owner, server, port, and channel from user
label1.Text = "Enter bot nick: ";
nick = textBox1.Text;
label2.Text = "Enter bot owner name: ";
owner = textBox2.Text;
label3.Text = "Enter server name: ";
label4.Text = "Enter port number: ";
if (textBox4.Text != "")
port = Convert.ToInt32(textBox4.Text);
label5.Text = "Channel: ";
chan = textBox5.Text;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void connectToIrc()
{
//Connect to irc server and get input and output text streams from TcpClient.
server = textBox3.Text;
port = Convert.ToInt32(textBox4.Text);
sock.Connect("chat.eu.freenode.net", port);//server, port);
if (!sock.Connected)
{
Console.WriteLine("Failed to connect!");
return;
}
input = new System.IO.StreamReader(sock.GetStream());
output = new System.IO.StreamWriter(sock.GetStream());
//Starting USER and NICK login commands
output.Write(
"USER " + nick + " 0 * :" + owner + "\r\n" +
"NICK " + nick + "\r\n"
);
output.Flush();
//Process each line received from irc server
for (buf = input.ReadLine(); ; buf = input.ReadLine())
{
//Display received irc message
Console.WriteLine(buf);
//Send pong reply to any ping messages
if (buf.StartsWith("PING ")) { output.Write(buf.Replace("PING", "PONG") + "\r\n"); output.Flush(); }
if (buf[0] != ':') continue;
/* IRC commands come in one of these formats:
* :NICK!USER@HOST COMMAND ARGS ... :DATA\r\n
* :SERVER COMAND ARGS ... :DATA\r\n
*/
//After server sends 001 command, we can set mode to bot and join a channel
if (buf.Split(' ')[1] == "001")
{
output.Write(
"MODE " + nick + " +B\r\n" +
"JOIN " + chan + "\r\n"
);
output.Flush();
}
}
}
private void button1_Click(object sender, EventArgs e)
{
connectToIrc();
}
}
}
例如,我输入chat.eu.freenode.net
服务器名称和端口 6667。
如果我通过 MIRC 程序进入这个服务器,它就可以工作。
但是在我的程序中,在FOR
循环中进行了 3-4 次迭代后,我在这一行得到了异常 null:
if (buf.StartsWith("PING "))
变量buf
是null
。
首先,它会进行几次迭代,然后在执行命令 3-5 次后:continue;
然后等待将近 15 秒,然后跳到该行:
if (buf.StartsWith("PING "))
并抛出异常空消息。
你调用的对象是空的
System.NullReferenceException was unhandled
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=Irc Bot
How can solve it ?