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.

EnderMHPosted Jan 5, 2025, 12:30 PM
Thanks! using the youtbe video and this article, i made my own app! thank you!
daniel ruanePosted Feb 3, 2022, 11:37 AM
Https://www.youtube.com/watch?v=BDVfpPq3weo this is his youtube video on how to do it
Philippe Boutremans, MD-MBAPosted Jan 16, 2022, 7:44 AM
Your code is incomplete, please when posting examples, try at least to be complete otherwise it's a waste of time. there\s MANY errors when running this
Suman RajPosted Dec 27, 2019, 12:24 AM
Please add screenshots
Voice ReflectionPosted Jan 16, 2018, 1:13 PM
Hi. eplocal where come from?
Pariwesh kumarPosted Sep 27, 2016, 6:01 AM
I am trying to communicate with node server putting ip and port to that server and passing json but no response is coming back
mohamed mohideenPosted Nov 12, 2014, 7:25 AM
how to add a callback function MessageCallBack
Asha Kumari DPosted Feb 21, 2014, 12:17 AM
Hi, i'm getting System.Net.Sockets.SocketException, a request to send or recieve data was disallowed because the socket was not connected and address was not supplied in the code which you have given can plz tell me how to solve this exception.
mzwe dlaminiPosted Jan 15, 2014, 7:31 AM
nice program
Hitesh chotaliyaPosted Jan 3, 2014, 4:18 AM
Nice Article
EDSON SCHEFFERPosted Oct 29, 2013, 2:55 PM
copy is easy...
Ye HtutPosted Jul 25, 2013, 5:36 AM
"sck" doesn't exist in the current context error show. I don't know how to solve. I also have used System.Net and System.Net.Scokets
Ye HtutPosted Jul 25, 2013, 5:36 AM
sck = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp); sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Dinesh BeniwalPosted Jun 25, 2013, 4:58 AM
Good Work, Welcome to the C# Corner Ripon.
Kundan KumarPosted Jun 24, 2013, 9:37 AM
Pls try to add running application with this nice article, It will make very good sense.