Using SmartIrc4net - IrcConnection
(Page 2 of 4 )
The first layer of SmartIrc4net is the IrcConnection class. This class is very basic. It contains a handful of methods that do things like connect and disconnect from the server, as well as a few properties that you can access and a few events that you can respond to. Here's the code required to connect to a given server:
using Meebey.SmartIrc4net;
using System;
using System.Collections.Generic;
using System.Text;
class ConnectionDemo
{
private IrcConnection irc = new IrcConnection();
private string server = "irc.freenode.com";
private int port = 6667;
private string channel = "#smartirc4net_test";
static void Main()
{
ConnectionDemo demo = new ConnectionDemo();
}
public ConnectionDemo()
{
irc.Connect(server, port);
irc.WriteLine(Rfc2812.Nick("CSharp"), Priority.Critical);
irc.WriteLine(Rfc2812.User("CSharp", 0, "CSharp Bot"),
Priority.Critical);
irc.WriteLine(Rfc2812.Join(channel));
irc.Listen();
}
}
The first line of the code points to the library, as you can see. We then create a class and provide a static Main method, which creates an instance of the class. Four member variables are created. One holds our IrcConnection instance, and the other three contain the server to connect to, the port to use and the channel to join. In the constructor, the Connect method of IrcConnection is called, and the server and port to use are passed as arguments.
Upon connecting to the server, we must provide a nickname. We do this by using WriteLine:
irc.WriteLine(Rfc2812.Nick("CSharp"), Priority.Critical);
The WriteLine method writes a complete line to the server. Here, we provide two arguments. The first argument is a string containing the contents of the line. While it is always possible to provide the raw IRC command for this, the static method Nick of the Rfc2812 object serves as a nice shortcut to this. All we have to do is provide the nickname itself. Notice, however, that RFC 2812 is used. This is one of the "new" RFCs intended to improve on the original RFC 1459. That said, keep in mind that RFC 1459 is still the official IRC RFC.
The second argument we pass makes use of the Priority enumeration. This enumeration contains the members Low, BelowMedium, Medium, AboveMedium, High and Critical. Since we absolutely must provide a nickname as soon as possible (or else we'll be disconnected), Critical is passed.
A username, userlevel and real name are then specified using WriteLine and User, and the priority is again set to Critical. Next, the application joins the channel specified in the channel string. Finally, the Listen method is called. The Listen method provides an infinite loop wherein data is read from the server as long as the application is still connected. Optionally, a Boolean can be passed as an argument. If false is passed, the method will return if there are no more messages to be received. The ListenOnce method also provides this functionality.
Of course, our application has a slight problem. When the server pings the application to make sure that it is still connected, our application doesn't respond. However, this is easily fixed. We simply have to respond to the server when we receive a ping message. To do this, we need to examine the incoming messages. While we could always stuff everything in one loop, there is no need to do this in SmartIrc4net. The library raises an event each time a line is received. All we have to do is respond to this. Here, we create a method that will handle incoming messages and examine them for ping messages:
void OnReadLine(object sender, ReadLineEventArgs e)
{
if (e.Line.StartsWith("PING"))
{
string server = e.Line.Split(' ')[1];
irc.WriteLine("PONG "+ server, Priority.Critical);
Console.WriteLine("Responded to ping at {0}.",
DateTime.Now.ToShortTimeString());
}
}
Notice how we are dealing with a ReadLineEventArgs object. This object contains a Line property, which simply contains the received line.
Now we have to hook our event handler up to the appropriate event. Do this in the constructor, like this:
public ConnectionDemo()
{
irc.OnReadLine += new ReadLineEventHandler(OnReadLine);
irc.Connect(server, port);
irc.WriteLine(Rfc2812.Nick("CSharp"), Priority.Critical);
irc.WriteLine(Rfc2812.User("CSharp", 0, "CSharp Bot"),
Priority.Critical);
irc.WriteLine(Rfc2812.Join(channel));
irc.Listen();
}
Several other events are available to us as well, such as OnConnecting, OnConnected and OnDisconnected. Let's respond to these events, and let's restructure the application so that we register with the server and join the specified channel when the OnConnected event is raised. The new constructor should look like this:
public ConnectionDemo()
{
irc.OnConnected += new EventHandler(OnConnected);
irc.OnConnecting += new EventHandler(OnConnecting);
irc.OnDisconnected += new EventHandler(OnDisconnected);
irc.OnReadLine += new ReadLineEventHandler(OnReadLine);
irc.Connect(server, port);
}
Here are the additional event handlers. Each writes a message to the console indicating the status of the application:
void OnConnected(object sender, EventArgs e)
{
Console.WriteLine("Connected.");
irc.WriteLine(Rfc2812.Nick("CSharp"), Priority.Critical);
irc.WriteLine(Rfc2812.User("CSharp", 0, "CSharp Bot"),
Priority.Critical);
irc.WriteLine(Rfc2812.Join(channel));
irc.Listen();
}
void OnConnecting(object sender, EventArgs e)
{
Console.WriteLine("Connecting to {0}.", server);
}
void OnDisconnected(object sender, EventArgs e)
{
Console.WriteLine("Disconnected.");
}
We can also modify the application to handle connection failures. Our IrcConnection object can be configured so that it automatically retries a failed connection attempt and automatically reconnects upon being disconnected. Of course, the library won't try to reconnect forever. Some basic error handling for this situation would be nice:
irc.AutoRetry = true;
irc.AutoRetryDelay = 10;
irc.AutoReconnect = true;
try
{
irc.Connect(server, port);
}
catch (Exception e)
{
Console.WriteLine("Failed to connect:n"+ e.Message);
Console.ReadKey();
}
The AutoRetryDelay property sets the interval between connection attempts.
Next: IrcCommands >>
More .NET Articles
More By Peyton McCullough