Simple VB.NET and CSharp IRC Client

I’ve noticed a lot of hits on my old broken vb.net irc example. So I made a new working one in both vb and csharp. Enjoy these commented examples!

VB.NET:

Namespace ircclient
	Class MainClass
		Public Shared Sub Main(args As String())
			Dim port As Integer
			Dim buf As String, nick As String, owner As String, server As String, chan As String
			Dim sock As New System.Net.Sockets.TcpClient()
			Dim input As System.IO.TextReader
			Dim output As System.IO.TextWriter

			'Get nick, owner, server, port, and channel from user
			Console.Write("Enter bot nick: ")
			nick = Console.ReadLine()
			Console.Write("Enter bot owner name: ")
			owner = Console.ReadLine()
			Console.Write("Enter server name: ")
			server = Console.ReadLine()
			Console.Write("Enter port number: ")
			port = Convert.ToInt32(Console.ReadLine())
			Console.Write("Channel: ")
			chan = Console.ReadLine()

			'Connect to irc server and get input and output text streams from TcpClient.
			sock.Connect(server, port)
			If Not sock.Connected Then
				Console.WriteLine("Failed to connect!")
				Return
			End If
			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 & vbCr & vbLf & "NICK " & nick & vbCr & vbLf)
			output.Flush()

			'Process each line received from irc server
			buf = input.ReadLine()
			While True

				'Display received irc message
				Console.WriteLine(buf)

				'Send pong reply to any ping messages
				If buf.StartsWith("PING ") Then
					output.Write(buf.Replace("PING", "PONG") & vbCr & vbLf)
					output.Flush()
				End If
				If buf(0) <> ":"C Then
					Continue While
				End If

				' 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(" "C)(1) = "001" Then
					output.Write("MODE " & nick & " +B" & vbCr & vbLf & "JOIN " & chan & vbCr & vbLf)
					output.Flush()
				End If
				buf = input.ReadLine()
			End While
		End Sub
	End Class
End Namespace

C#:


using System;

namespace ircclient
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			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;
			
			//Get nick, owner, server, port, and channel from user
			Console.Write("Enter bot nick: ");
			nick = Console.ReadLine();
			Console.Write("Enter bot owner name: ");
			owner = Console.ReadLine();
			Console.Write("Enter server name: ");
			server = Console.ReadLine();
			Console.Write("Enter port number: ");
			port = Convert.ToInt32(Console.ReadLine());
			Console.Write("Channel: ");
			chan = Console.ReadLine();
			
			//Connect to irc server and get input and output text streams from TcpClient.
			sock.Connect(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();
				}
			}
		}
	}
}

20 thoughts on “Simple VB.NET and CSharp IRC Client

  1. Pingback: VB.NET IRC Client | Jakash3's Blog

    • Send “NAMES #ChannelName” and the server will send something like:
      “:servername 353 yournick = #ChannelName :foonick barnick &foobaradmin”
      Where the names are separated by spaces in the data field. It may send more lines containing more names, and finally a message with the command 336 will be sent after the last set of names.

    • These are console applications, no other files are needed. You should be able to copy and paste the Main functinos directly into a new csharp or vb console projects.

  2. Hey. I’m using a heavily modified version of your old code. (as I liked it better for some odd reason). Every few hours or so, the bot disconnects, and it’s unable to reconnect. Is there a way to reinit the whole program/bot if there is a unhandled error/socket disconnects?
    Thanks,

    x-treme

  3. Pingback: פרויקט שרת-קליינט mIRC (בוט) ב-VB.NET | Yoni Works SN No.1

      • Because vbCrLf (Carriage return + Line Feed) signals the end of the line so until you send this, the server is waiting for more data from you. When the PING comes in, the example code is automatically replying to it and adding vbCrLf on the end, signaling the end of the data.

  4. Because you do ‘buf = input.ReadLine()’ at the end of the while loop and do ‘Continue While’ when buf does not start with “:” you will never read the next line after receiving a line that does not start with “:”, a line like PING. Instead you should do ‘buf = input.ReadLine()’ as the first thing in your while loop, than you also do not need (and must remove) the one before the while making the code one line shorter ;)

  5. I wish I knew how I could use this code… Where to I call the functions? When I start the application is just ends directly.

  6. I will right away seize your rss feed as I can’t to find your email subscription link or e-newsletter service. Do you have any? Kindly permit me know so that I could subscribe. Thanks.

  7. This sort-of works, not really, when I run it. 10 lines get printed out to the Console, i join the server, it works, i get a welcom message, i join the channel, it gives me a list of users, but the last line ends with “:End of /NAMES list” and then it has a stroke the next time it runs “buf = input.ReadLine()” in the for loop. There’s no unhandled exception. Wrapping it in a try block does nothing. The window stays open but the code just completely stops running.

  8. I get this error message:

    Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.

    Pointed at output.Flush() in:

    If buf.StartsWith(“PING “) Then
    output.Write(buf.Replace(“PING”, “PONG”) & vbCr & vbLf)
    output.Flush()
    End If

    any suggestions?

  9. figured i would leave my code for a template on how i used this in a form with treading
    Important please use debug mode code is still buggy when closing connection and may run in background when used outside debug mode
    Sorry in advance for long post

    Imports System.Net
    Imports System.Text
    Imports System.Net.Sockets
    Imports System.IO
    Imports System

    Public Class Form1
    Dim mains As New Class1
    Dim list As New List(Of Threading.Thread)
    Dim butt As Boolean = False

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    For Each Item In list
    Item.Abort()

    Next
    list.Clear()
    End Sub
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Control.CheckForIllegalCrossThreadCalls = False
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ‘connection to channel can use multiple channels and receive messages from multiple channels
    list.Clear()
    For i = 0 To TrackBar1.Value – 1
    Dim flood As New Threading.Thread(AddressOf conn)
    flood.Start()
    list.Add(flood)
    Next
    End Sub
    Sub conn()
    Dim port As Integer
    Dim buf As String, nick As String, owner As String, server As String, chan As String
    Dim sock As New System.Net.Sockets.TcpClient()
    Dim input As System.IO.TextReader
    Dim output As System.IO.TextWriter
    Dim pass As String
    butt = New Boolean = False
    ‘Get nick, owner, server, port, and channel from user
    ‘Console.Write(“Enter bot nick: “)
    nick = TextBox1.Text
    ‘ Console.Write(“Enter bot owner name: “)
    owner = TextBox1.Text
    pass = TextBox2.Text
    ‘ Console.Write(“Enter server name: “)
    server = TextBox3.Text
    ‘ Console.Write(“Enter port number: “)
    port = TextBox4.Text
    ‘ Console.Write(“Channel: “)
    chan = TextBox5.Text

    ‘Connect to irc server and get input and output text streams from TcpClient.
    sock.Connect(server, port)
    If Not sock.Connected Then
    Label1.Text = “Failed to connect!”
    Return
    End If
    input = New System.IO.StreamReader(sock.GetStream())
    output = New System.IO.StreamWriter(sock.GetStream())

    ‘Starting USER and NICK login commands
    output.Write(“Pass ” & pass & vbCr & vbLf & “NICK ” & nick & vbCr & vbLf & owner & vbCr & vbLf)
    output.Flush()

    ‘Process each line received from irc server
    buf = input.ReadLine()
    While True

    ‘Display received irc message
    ListBox1.Items.Add(buf)

    ‘Send pong reply to any ping messages
    ‘ not sure how but messages can still send with all of this code commented out when connecting
    If buf.StartsWith(“PING “) Then
    output.Write(buf.Replace(“PING”, “PONG”) & vbCr & vbLf)
    ‘output.Write(“PRIVMSG ” + chan + TextBox6.Text & vbCr & vbLf)
    output.Flush()

    End If
    ‘If butt = True Then
    ‘ output.Write(“PRIVMSG ” & chan & ” :” & TextBox6.Text.ToString & vbCr & vbLf)
    ‘ Label1.Text = TextBox6.Text & ” message send”
    ‘ output.Flush()
    ‘ butt = False
    ‘End If
    If buf(0) “:”c Then
    Continue While
    End If
    If buf.Split(” “c)(1) = “001” Then
    output.Write(“MODE ” & nick & ” +B” & vbCr & vbLf & “JOIN ” & chan & vbCr & vbLf)
    output.Flush()
    End If

    ‘ 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

    buf = input.ReadLine()
    End While
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    ‘butt = True
    ‘ process for sending messages with out waiting for updates
    ‘ basicly the idea is closing all existing connections for a second then reopen them to send the message
    For Each Item In list
    Item.Abort()
    Next
    list.Clear()
    For i = 0 To TrackBar1.Value – 1
    Dim flood As New Threading.Thread(AddressOf send)
    flood.Start()
    list.Add(flood)
    Next

    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    For Each item In list ‘disconnecting client
    item.Abort()
    Next
    End Sub

    Sub send()
    Dim port As Integer
    Dim buf As String, nick As String, owner As String, server As String, chan As String
    Dim sock As New System.Net.Sockets.TcpClient()
    Dim input As System.IO.TextReader
    Dim output As System.IO.TextWriter
    Dim pass As String
    butt = New Boolean = False
    ‘Get nick, owner, server, port, and channel from user
    ‘Console.Write(“Enter bot nick: “)
    nick = TextBox1.Text
    ‘ Console.Write(“Enter bot owner name: “)
    owner = TextBox1.Text
    pass = TextBox2.Text
    ‘ Console.Write(“Enter server name: “)
    server = TextBox3.Text
    ‘ Console.Write(“Enter port number: “)
    port = TextBox4.Text
    ‘ Console.Write(“Channel: “)
    chan = TextBox5.Text

    ‘Connect to irc server and get input and output text streams from TcpClient.
    sock.Connect(server, port)
    If Not sock.Connected Then
    Label1.Text = “Failed to connect!”
    Return
    End If
    input = New System.IO.StreamReader(sock.GetStream())
    output = New System.IO.StreamWriter(sock.GetStream())

    ‘Starting USER and NICK login commands
    output.Write(“Pass ” & pass & vbCr & vbLf & “NICK ” & nick & vbCr & vbLf & owner & vbCr & vbLf)
    output.Flush()

    ‘Process each line received from irc server
    buf = input.ReadLine()
    While True

    ‘Display received irc message
    ListBox1.Items.Add(buf)

    ‘Send pong reply to any ping messages

    If buf.StartsWith(“PING “) Then
    output.Write(buf.Replace(“PING”, “PONG”) & vbCr & vbLf)
    ‘output.Write(“PRIVMSG ” + chan + TextBox6.Text & vbCr & vbLf)
    output.Flush()

    End If
    If butt = True Then ‘supposed to send when button is pressed
    Dim splits() As String = Split(TextBox6.Text, vbCrLf)
    For Each line In splits ‘ if multiline is enabled then you can dictate it to send multiple messages at once using enter(vbCrLf)
    output.Write(“PRIVMSG ” & chan & ” :” & line.ToString & vbCr & vbLf)
    Label1.Text = TextBox6.Text & ” message send”
    output.Flush()
    ListBox1.Items.Add(line.ToString)
    Next
    ‘output.Write(“PRIVMSG ” & chan & ” :” & TextBox6.Text.ToString & vbCr & vbLf)
    ‘Label1.Text = TextBox6.Text & ” message send”
    ‘output.Flush()
    butt = False
    End If
    If buf(0) “:”c Then
    Continue While
    End If
    If buf.Split(” “c)(1) = “001” Then
    output.Write(“MODE ” & nick & ” +B” & vbCr & vbLf & “JOIN ” & chan & vbCr & vbLf)
    output.Flush()
    End If

    ‘ 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

    buf = input.ReadLine()
    End While
    End Sub
    End Class

  10. Pingback: En IRC-klient skriven i VB.net och CSharp – Tekniktoppen

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: