How To Make a Chat Application in C#

This project shows you how to make a chat application step-by-step in Microsoft Visual C#. This project uses a UDP (User Datagram Protocol) Socket connection between two chat applications. This chat application can work within the same network or across networks.

However, in this project, I shall be focusing on how to communicate asynchronously with two chat applications. An Asynchronous Communication system is a way of communicating where both sides can communicate simultaneously with each other. For example, a telephone call is an example of asynchronous communication system.

I am going to show you step-by-step skipping no step.

Step 1: First make a project, go to Microsoft Visual C# then create a project.

Step 2: Design the Chat Application form with TextBox, label, button and group boxes.

Give the form objects names as in the following:

Your IP textbox name = textLocalIp,
Your Port textbox name = textLocalPort,
Friend's IP textbox name = textFriendsIp
Friend's Port textbox name = textFriendsPort
Listbox Message name = listMessage,
Textbox for Message sending name = textMessage,
Start Button name = buttonStart,
Send Button name = buttonSend

Step 3: Add 2 namespaces to the project.

using System.Net;
using System.Net.Sockets;

Step 4 : Add the following code for the form load, double-click on the form then write the following code.

// set up socket
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

// get own IP
textLocalIp.Text = GetLocalIP();
textFriendsIp.Text = GetLocalIP();

Then add a method GetLocalIP() as follows. This method will return the Local IP address to the text boxes.

// Return your own IP
private string GetLocalIP()
{
    IPHostEntry host;
    host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (IPAddress ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            return ip.ToString();
        }
    }
    return "127.0.0.1";
}

Step 5: Add the following code under the Start Button click event.

try
{ 
    // binding socket
    epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), 
    Convert.ToInt32(textLocalPort.Text));
    sck.Bind(epLocal);
    // connect to remote IP and port
    epRemote = new IPEndPoint(IPAddress.Parse(textFriendsIp.Text), 
    Convert.ToInt32(textFriendsPort.Text));
    sck.Connect(epRemote);
    // starts to listen to an specific port
    buffer = new byte[1500];
    sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new
    AsyncCallback(MessageCallBack), buffer);
    // release button to send message
    buttonSend.Enabled = true;
    buttonStart.Text = "Connected";
    buttonStart.Enabled = false;
    textMessage.Focus();
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

Now, you need to add a callback function MessageCallBack. Just add the following code.

try
{
    int size = sck.EndReceiveFrom(aResult, ref epRemote);
    // check if theres actually information 
    if (size > 0) 
    {
        // used to help us on getting the data
        byte[] receivedData = new byte[1464];
        // getting the message data
        receivedData = (byte[])aResult.AsyncState;
        // converts message data byte array to string
        ASCIIEncoding eEncoding = new ASCIIEncoding();
        string receivedMessage = eEncoding.GetString(receivedData);
        // adding Message to the listbox
        listMessage.Items.Add("Friend: " + receivedMessage);
    }
    // starts to listen the socket again
    buffer = new byte[1500];
    sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch (Exception exp)
{
    MessageBox.Show(exp.ToString());
}

Step 6: In this step you need to add the following code for the send button click event.

try
{ 
    // converts from string to byte[]
     System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
     byte[] msg = new byte[1500];
     msg = enc.GetBytes(textMessage.Text);
     // sending the message
     sck.Send(msg);
     // add to listbox
     listMessage.Items.Add("You: " + textMessage.Text);
     // clear txtMessage
     textMessage.Clear();
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

Step 7: Now build the project by clicking the Build menu then the Build Solution sub-menu. And now go to the project folder and go inside the project folder to the bin folder then bin debug. In the debug folder you will see the ChatApps.exe file.

Open two instances for testing purposes in your computer, then give a different Port number as you are listening in the same IP. Then connect both Applications and start sending messages. I hope you will enjoy this project. If you want to chat with your friends or colleagues in the LAN or the same network then give them a copy of ChattApps.exe and now you will be able to chat from a different computer.


Similar Articles