Skip to main content

How To Create C# Chat Application

Hello Geeks .. Today I gonna show you How to make a Chat Application Using Microsoft C#.NET 5.0 .
You Can Use Older Versions Since there is nothing special in the application that only belongs to C# 5.0 .

This Application Was Created To Allow Two Computers To "Chat" Using IP Addresses Also you Can Open two Clients On The Same Computer and Use Same IP Address But Different Port.. It is simple and Easy to Use And Develop .. I also Uploaded The Full Working Project With It's Source Code On MediaFire.. You Will Find The Link At The End Of the Post :)
C# Chat Application

First Design The Form : As Seen In The Above Picture And Give Name To The Buttons and Text Boxes and The ListBox 

In GroupBox Me : txtLocalIP and txtLocalPort
In GroupBox Friend : txtRemoteIP and txtRemotePort
Name Buttons : BtnConnect , BtnSend
Name ListBox : ListMessages.
Name The below Text Box As  TxtMessage

Steps To Implement The Code Yourself :

First Add Those Two Namespaces : 

Using System.Net;
Using System.Net.Sockets;

Inside The Form Class Create Instances Of The Following : 

 Socket mySocket;
 EndPoint epLocal , epRemote;
  byte [] buffer;

Create A private string method To Get The Local IP of The Computer :

         private string GetLocalIP()
        {
            IPHostEntry myHost;
            myHost = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in myHost.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                    return ip.ToString();
            }
            return "127.0.0.1";
        }

Create Another Method With Instance IAsyncResult : 

 private void MessageCallBack(IAsyncResult aResult)
        {
            try
            {
                byte[] RecivedData = new byte[1500];
                RecivedData = (byte[])aResult.AsyncState;

                //converting byte[] into string
                ASCIIEncoding aEncoding = new ASCIIEncoding();
                string RecivedMessage = aEncoding.GetString(RecivedData);

                //Adding this message to listbox
                ListMessages.Items.Add("Friend : " + RecivedMessage);

                buffer = new byte[1500];
                mySocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

Now In The Form_Load Field .. Set Up The Socket and Get The User IP : 

            //set up socket
            mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            mySocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            //get user IP
            txtLocalIP.Text = GetLocalIP();
            txtRemoteIP.Text = GetLocalIP();

Start Implementing Code For The Connect Button : 

 private void BtnConnect_Click(object sender, EventArgs e)
        {
            //binding sockets
            epLocal = new IPEndPoint(IPAddress.Parse(txtLocalIP.Text), Convert.ToInt32(txtLocalPort.Text));
            mySocket.Bind(epLocal);

            //Connecting To Remote IP
            epRemote = new IPEndPoint(IPAddress.Parse(txtRemoteIP.Text), Convert.ToInt32(txtRemotePort.Text));
            mySocket.Connect(epRemote);

            //Listening TO specific Port
            buffer = new byte[1500];
            mySocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);

            //Announce When Connected
            BtnConnect.Text = "Connected";
            BtnConnect.Enabled = false;
        }

Implement Code For The Send Message Button : 

        private void btnSend_Click(object sender, EventArgs e)
        {
            //converting string messages to byte
            ASCIIEncoding aEncoding = new ASCIIEncoding();
            byte[] SendingMessage = new byte[1500];
            SendingMessage = aEncoding.GetBytes(txtMessage.Text);

            //sending Encoding message
            mySocket.Send(SendingMessage);

            //adding to listbox
            ListMessages.Items.Add("ME : " + txtMessage.Text);
            txtMessage.Text = null;

        }
Here You Can Download The Full Working Application And It's Source Code :
The Download Link :  C# Chat Application Using IP Address

I Hope It's Useful For You People .. Best Wishes :)

Related Posts : 

Comments

Popular posts from this blog

C# Full Pharmacy Project With Source code

Hello Geeks .. This post is one of our completely Free Projects  .. It is a Pharmacy Project that can perform a lot of operations you can also find the (.dll) files for the working Barcode Reader Machines in your country and add it to the project .

How To Create A Change Password Form in a C# Application

Hello Geeks .. This little post is a free sample C#  Windows Form that can be used to change password in a SQL Database .