I'm trying to write a simple IRC bot but I'm getting null exception why is
that?
This is my code for 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();
}
}
}
For example I enter chat.eu.freenode.net for the server name and 6667 for
the port.
And it's working if I'm entering this server through the MIRC program.
But in my program after 3-4 iterations in the FOR loop I'm getting
exception null on this line:
if (buf.StartsWith("PING "))
The variable buf is null.
First it's doing the iterations some times then after 3-5 times its doing
the command: continue; and then hang on for almost 15 seconds then its
jumping to the line:
if (buf.StartsWith("PING "))
and throw the exception null message.
Object reference not set to an instance of an object
System.NullReferenceException was unhandled
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=Irc Bot
How can solve it ?
No comments:
Post a Comment