Domov > C#, Code, Windows > C# GUI IRC Client

C# GUI IRC Client

junij 28, 2010 Komentiraj Go to comments

I write some irc client well i was trying, but i didn’t finish it however here is the code… i was coding just for fun, and i have enough of this project.. it is UNSTABLE, some crapy code and so as i excepter some random crash, the problem is in events, from thread to gui thread and in index of treeview…
And as i say it is UNFINISHED and BUGY :P

Tuki je pa en projekt moj nedokončan v C#.

Language: C#

OS: Windows

File:  MainForm.cs

/*
 * Created by SharpDevelop.
 * User: upd
 * Date: 17.6.2010
 * Time: 21:21
 * 
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.IO;

namespace IRC_Client
{
	/*
	class Servers
	{
		List<Channel> channels = new List<Channel>();
		public string Name;
		
		public Servers(string text)
		{
			Name = text;
		}
	}
	*/
	class Channel
	{
		public List<User> users = new List<User>();
		public string Name;
		public string topic;
		public ArrayList msg = new ArrayList();
		
		public Channel(string text)
		{
			Name = text;
		}
		
		public void AddTopic(string text)
		{
			topic = text;
		}
		
		public void AddMsg(string nick, string text)
		{
			msg.Add("<" + nick + "> " + text + "\r\n");
		}
		
		public void AddInfo(string nick, string text)
		{
			msg.Add(nick + " " + text + "\r\n");
		}
	}
	
	class User
	{
		public string Name;
		
		public User(string text)
		{
			Name = text;			
		}
	}
	
	public partial class MainForm : Form
	{
		public delegate void UpdateChanCallback();
	//	public delegate void UpdateUserCallback();
	//	public delegate void RemoveUserCallback(string text);
		public delegate void UpdateTopicCallback(string text);
		public delegate void UpdateMsgCallback(int index);
		public delegate void SelectChanCallback(int index);
		public delegate void UpdateUsersCallback(string Name);
		
//		List<Servers> servers = new List<servers>();
		List<Channel> channels = new List<Channel>();
		int selected_ch;
		private byte[] buf = new byte[1024];
		
		StreamWriter ircWriter;
		StreamReader ircReader;
		
		public MainForm()
		{
			InitializeComponent();
		}
		
		void BconnectClick(object sender, EventArgs e)
		{
			Thread t = new Thread(connect);
			t.Start();
		}
		
		void connect()
		{
			IPHostEntry iphostinfo = Dns.GetHostEntry("irc.freenode.org");
			IPAddress ipaddr = iphostinfo.AddressList[0];
			IPEndPoint ep = new IPEndPoint(ipaddr, 6667);
			Socket sock;
			
			sock = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
			
			sock.Connect(ep);
			
			ircWriter = new StreamWriter(new NetworkStream(sock));
			ircReader = new StreamReader(new NetworkStream(sock));
			
			ircWriter.WriteLine(String.Format("USER updx 0 * :I'm here now!"));
			ircWriter.Flush();
			
			ircWriter.WriteLine(String.Format("NICK updx"));
			ircWriter.Flush();
			
			while(true)
			{
				string ircCmd;
				
				while((ircCmd = ircReader.ReadLine()) != null )
				{
					string[] cmd = new String[ircCmd.Split(' ').Length];
					cmd = ircCmd.Split(' ');
					
					if ( cmd[0].Substring(0,1) == ":" )
					{
						switch (cmd[1])
						{
							case "376": IrcEndOfMotd(cmd); break;
							case "353": IrcNamesList(cmd); break;
							case "332": IrcTopic(ircCmd); break;
							case "TOPIC": IrcTopicChanged(ircCmd); break;
							case "PRIVMSG": IrcPrivMsg(ircCmd); break;
							case "JOIN": IrcJoin(cmd); break;
							case "PART": IrcPart(cmd); break;
							case "MODE": IrcMode(cmd); break;
							case "NICK": IrcNickChange(cmd); break;
							case "KICK": IrcKick(cmd); break;
							case "QUIT": IrcQuit(cmd); break;
							case "NOTICE": IrcNotice(cmd); break;
							default : IrcServerMessage(ircCmd); break;
							/*
						case "JOIN": this.IrcJoin(commandParts); break;
                        case "PART": this.IrcPart(commandParts); break;
                        case "MODE": this.IrcMode(commandParts); break;
                        case "NICK": this.IrcNick(commandParts); break;
                        case "KICK": this.IrcKick(commandParts); break;
                        case "QUIT":
                        */
						}
					}
					else if ( cmd[0] == "PING" )
					{
						IrcPing(cmd);
					}
					else if ( cmd[0] == "ERROR" )
					{
						IrcErrorClose(cmd);
					}
				}
			}
		}
			
		private void IrcEndOfMotd(string[] command)
		{
			ircWriter.WriteLine(String.Format("JOIN #updx"));
			ircWriter.Flush();
			
			ircWriter.WriteLine(String.Format("JOIN #lovers"));
			ircWriter.Flush();
			
			ircWriter.WriteLine(String.Format("JOIN ##windows"));
			ircWriter.Flush();
		}
		
		private void IrcNamesList(string[] command)
		{
			int usr = 5;
			MessageBox.Show("Searching for channel " + command[4]);
			int index = search_for_channel(command[4]);
			
			if ( index == -1 )
			{
				MessageBox.Show("Channel " + command[4] + " not finded adding it");
				channels.Add(new Channel(command[4]));
				index = channels.Count-1;
				chant.Invoke(new UpdateChanCallback(this.UpdateChan));
		//		chant.Invoke(new UpdateChanCallback(this.UpdateChan));
		//		chant.Invoke(new SelectChanCallback(this.SelectChan), index);
			}

			if ( command[5].Substring(0,1) == ":")
			{
				command[5] = command[5].Remove(0,1);
			}
			
			while ( usr < command.Length )
			{
				if ( command[usr].Substring(0,1) == "@" )
				{
					channels[index].users.Insert(0, new User(command[usr]));
				}
				else
				{
					channels[index].users.Add(new User(command[usr]));
				}
				usr++;
			}
			chant.Invoke(new SelectChanCallback(this.SelectChan), index);
		}

		private void UpdateChan()
		{
			MessageBox.Show("Adding channel to treeview " + channels[channels.Count-1].Name);
			chant.Nodes.Add(channels[channels.Count-1].Name);
		}
		
		private void SelectChan(int index)
		{
			MessageBox.Show("Selecting channel " + channels[index].Name);
			chant.SelectedNode = chant.Nodes[index];
		}
		
		private void IrcTopic(string buf)
		{
			int at;
			
			if ( buf.Substring(0,1) != ":" )
			{
				return;
			}
			buf = buf.Remove(0,1);
			
			string[] cmd = new String[buf.Split(' ').Length];
			cmd = buf.Split(' ');
			
			int index = search_for_channel(cmd[3]);
			
			if ( index == -1 )
			{
				channels.Add(new Channel(cmd[3]));
				index = channels.Count-1;
				chant.Invoke(new UpdateChanCallback(this.UpdateChan));
			}
			
			at = buf.IndexOf(":");
			buf = buf.Remove(0, at+1);
			
			channels[index].AddTopic(buf);
		}
		
		private void IrcTopicChanged(string buf)
		{
			int at;
			
			if ( buf.Substring(0,1) != ":" )
			{
				return;
			}
			buf = buf.Remove(0,1);
			
			string[] cmd = new String[buf.Split(' ').Length];
			cmd = buf.Split(' ');
			
			int index = search_for_channel(cmd[2]);
			
			at = buf.IndexOf(":");
			buf = buf.Remove(0, at+1);
			
			channels[index].AddTopic(buf);
			
			if ( index == selected_ch )
			{
				topictxt.Invoke(new UpdateTopicCallback(this.UpdateTopic), buf);
			}
		}
		
		private void UpdateTopic(string text)
		{
			topictxt.Text = text;
		}
		
		private void IrcPrivMsg(string buf)
		{
			int at;
			string nick;
			
			if ( buf.Substring(0,1) != ":" )
			{
				return;
			}
			buf = buf.Remove(0,1);
			
			string[] cmd = new String[buf.Split(' ').Length];
			cmd = buf.Split(' ');
			
			int index = search_for_channel(cmd[2]);
			
			if ( index == -1 )
			{
				return;
			}
			
			at = cmd[0].IndexOf("!");
			if ( at <= 0 )
			{
				return;
			}
			nick = cmd[0].Substring(0, at);
			
			at = buf.IndexOf(":");
				
			buf = buf.Remove(0, at+1);
				
			channels[index].AddMsg(nick, buf);

			if ( selected_ch == index )
			{
				msgin.Invoke(new UpdateMsgCallback(this.UpdateMsg), index);
			}
		}

		private void UpdateMsg(int index)
		{
			msgin.Text = "";
			
			string buf = PrintMsg(index);
			
			if ( buf != null )
			{
				msgin.Text = buf;
			}
		}

		private void IrcJoin(string[] command)
		{
			string nick;
			string ch;
			int at;
			
			if ( command[0].Substring(0,1) != ":" )
			{
				return;
			}
			
			command[0] = command[0].Remove(0,1);
			
			if ( command[0].Substring(0,4) == "updx")
			{
				return;
			}

			at = command[0].IndexOf("!");
			if ( at <= 0 )
			{
				return;
			}
			
			// if @ in nick add at the top!
			nick = command[0].Substring(0, at);
					
			command[2] = command[2].Remove(0,1);					
			ch = command[2];
			
			int index = search_for_channel(ch);
			
			if ( index == -1 )
			{
				// this should not happend however create new channel..
				channels.Add(new Channel(ch));
				index = channels.Count-1;
			}
			channels[index].users.Add(new User(nick));
			
			channels[index].AddInfo(nick, "has joined " + channels[index].Name);

			if ( selected_ch == index )
			{
				msgin.Invoke(new UpdateMsgCallback(this.UpdateMsg), index);
				chant.Invoke(new UpdateUsersCallback(this.UpdateUserNew), nick);
			}
		}
		
		private void UpdateUserNew(string Name)
		{
			userl.Items.Add(Name);
		}
		
		private void IrcPart(string[] command)
		{
			string nick;
			string ch;
			int at;
			
			if ( command[0].Substring(0,1) != ":" )
			{
				return;
			}
			
			command[0] = command[0].Remove(0,1);
			
			if ( command[0].Substring(0,4) == "updx")
			{
				return;
			}

			at = command[0].IndexOf("!");
			if ( at <= 0 )
			{
				return;
			}
			
			// if @ in nick add at the top!
			nick = command[0].Substring(0, at);
					
			command[2] = command[2].Remove(0,1);					
			ch = command[2];
			
			int index = search_for_channel(ch);
			
			if ( index == -1 )
			{
				// this should not happend however create new channel..
				// channels.Add(new Channel(ch));
				// index = channels.Count-1;
			}
//			channels[index].users.Remove(nick);
//			channels.Remove(channels[index]);
//			channels[index].users.Add(new User(nick));
		}
		
		private void RemoveUser(string text)
		{
//			usert.Nodes.Remove();
//			usert.Nodes.Remove(text);
		}
		
		private void IrcMode(string[] command)
		{
			
		}
		
		private void IrcNickChange(string[] command)
		{
			
		}
		
		private void IrcKick(string[] command)
		{
			
		}
		
		private void IrcQuit(string[] command)
		{

		}
		
		private void IrcNotice(string[] command)
		{
			
		}
		
		private void IrcPing(string[] command)
		{
			string PingHash = "";
			for (int intI = 1; intI < command.Length; intI++)
			{
				PingHash += command[intI] + " ";
			}
			ircWriter.WriteLine("PONG " + PingHash);
			ircWriter.Flush();
		}
		
		private void IrcErrorClose(string[] command)
		{
			
		}
		
		private void IrcServerMessage(string buf)
		{
			
		}
		
		private void CheckUsers()
		{
			chant.Select();
		
			if (chant.SelectedNode != null)
			{
				// flush users on channel
				userl.Items.Clear();
			
				foreach (User user in channels[chant.SelectedNode.Index].users)
				{
					if (channels[chant.SelectedNode.Index].users != null )
					{
						userl.Items.Add(user.Name);
					}
				}
				
				// flush messager on channel
				msgin.Text = "";
				
				string buf = PrintMsg(chant.SelectedNode.Index);
				if ( buf != null )
				{
					msgin.Text = buf;
				}
				
				// flush topic for channel
				topictxt.Text = "";
				topictxt.Text = channels[chant.SelectedNode.Index].topic;
				
				selected_ch = chant.SelectedNode.Index;
			}
		}
		
		void TreechanAfterSelect(object sender, TreeViewEventArgs e)
		{
			CheckUsers();
		}
		
		private int search_for_channel(string text)
		{
			for ( int i = 0 ; i <  channels.Count ; i++)
			{
				if ( channels[i].Name == text )
				return i;
			}
			return -1;
		}
		
		private string PrintMsg(int index)
		{
			string buf = "";
			
			if ( channels[index].msg.Count <= 0 )
			{
				return null;
			}
			
			for ( int i = 0 ; i < channels[index].msg.Count ; i++ )
			{
				buf = buf + channels[index].msg[i];
			}
			return buf;
		}
		
		void MsgoutKeyDown(object sender, KeyEventArgs e)
		{
			string buf;
			string obuf;
			
			if ( e.KeyCode == Keys.Enter )
			{
				buf = msgout.Text;
				
				if ( buf.Substring(0,1) == "/")
				{
					buf = buf.Remove(0,1);
					
					msgout.Text = "";
					
					ircWriter.WriteLine(buf);
					ircWriter.Flush();

				}
				else
				{
					obuf = "PRIVMSG " + channels[selected_ch].Name + " :" + buf + "\r\n";
					channels[selected_ch].AddMsg("updx", buf);
					msgin.Invoke(new UpdateMsgCallback(this.UpdateMsg), selected_ch);
					
					msgout.Text = "";
					
					ircWriter.WriteLine(obuf);
					ircWriter.Flush();
					
				}
			}
		}
	}
}

File:  MainForm.Designed.cs

/*
 * Created by SharpDevelop.
 * User: upd
 * Date: 17.6.2010
 * Time: 21:21
 * 
 */
namespace IRC_Client
{
	partial class MainForm
	{
		/// <summary>
		/// Designer variable used to keep track of non-visual components.
		/// </summary>
		private System.ComponentModel.IContainer components = null;
		
		/// <summary>
		/// Disposes resources used by the form.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing) {
				if (components != null) {
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}
		
		/// <summary>
		/// This method is required for Windows Forms designer support.
		/// Do not change the method contents inside the source code editor. The Forms designer might
		/// not be able to load this method if it was changed manually.
		/// </summary>
		private void InitializeComponent()
		{
			this.bconnect = new System.Windows.Forms.Button();
			this.msgin = new System.Windows.Forms.TextBox();
			this.chant = new System.Windows.Forms.TreeView();
			this.nicktxt = new System.Windows.Forms.TextBox();
			this.msgout = new System.Windows.Forms.TextBox();
			this.topictxt = new System.Windows.Forms.TextBox();
			this.userl = new System.Windows.Forms.ListBox();
			this.SuspendLayout();
			// 
			// bconnect
			// 
			this.bconnect.Location = new System.Drawing.Point(893, 12);
			this.bconnect.Name = "bconnect";
			this.bconnect.Size = new System.Drawing.Size(178, 22);
			this.bconnect.TabIndex = 0;
			this.bconnect.Text = "Connect";
			this.bconnect.UseVisualStyleBackColor = true;
			this.bconnect.Click += new System.EventHandler(this.BconnectClick);
			// 
			// msgin
			// 
			this.msgin.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
			this.msgin.Location = new System.Drawing.Point(209, 40);
			this.msgin.Multiline = true;
			this.msgin.Name = "msgin";
			this.msgin.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
			this.msgin.Size = new System.Drawing.Size(678, 695);
			this.msgin.TabIndex = 1;
			// 
			// chant
			// 
			this.chant.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this.chant.Location = new System.Drawing.Point(12, 12);
			this.chant.Name = "chant";
			this.chant.Size = new System.Drawing.Size(191, 723);
			this.chant.TabIndex = 2;
			this.chant.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.TreechanAfterSelect);
			// 
			// nicktxt
			// 
			this.nicktxt.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this.nicktxt.Location = new System.Drawing.Point(12, 741);
			this.nicktxt.Name = "nicktxt";
			this.nicktxt.Size = new System.Drawing.Size(191, 22);
			this.nicktxt.TabIndex = 4;
			this.nicktxt.Text = "updx";
			// 
			// msgout
			// 
			this.msgout.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this.msgout.Location = new System.Drawing.Point(209, 741);
			this.msgout.Name = "msgout";
			this.msgout.Size = new System.Drawing.Size(862, 22);
			this.msgout.TabIndex = 5;
			this.msgout.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MsgoutKeyDown);
			// 
			// topictxt
			// 
			this.topictxt.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this.topictxt.Location = new System.Drawing.Point(209, 12);
			this.topictxt.Name = "topictxt";
			this.topictxt.Size = new System.Drawing.Size(678, 22);
			this.topictxt.TabIndex = 8;
			// 
			// userl
			// 
			this.userl.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this.userl.FormattingEnabled = true;
			this.userl.ItemHeight = 16;
			this.userl.Location = new System.Drawing.Point(893, 45);
			this.userl.Name = "userl";
			this.userl.Size = new System.Drawing.Size(178, 692);
			this.userl.TabIndex = 10;
			// 
			// MainForm
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(1083, 765);
			this.Controls.Add(this.userl);
			this.Controls.Add(this.topictxt);
			this.Controls.Add(this.msgout);
			this.Controls.Add(this.nicktxt);
			this.Controls.Add(this.chant);
			this.Controls.Add(this.msgin);
			this.Controls.Add(this.bconnect);
			this.Name = "MainForm";
			this.Text = "IRC Client";
			this.ResumeLayout(false);
			this.PerformLayout();
		}
		private System.Windows.Forms.ListBox userl;
		private System.Windows.Forms.TextBox msgin;
		private System.Windows.Forms.TextBox nicktxt;
		private System.Windows.Forms.TextBox msgout;
		private System.Windows.Forms.TextBox topictxt;
		private System.Windows.Forms.TreeView chant;
		private System.Windows.Forms.Button bconnect;
	}
}

Categories: C#, Code, Windows
  1. Babau
    november 23, 2011 at 1:37 popoldan | #1

    Hwllo man
    I try to retrieve list with users from a channel but dont know how.
    Can u help me pls? In c# i work…
    luci15ian@gmail.com
    Thx.

  1. No trackbacks yet.

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.