3
Posted August 25, 2012 by George in C#
 
 

How to Make a Simple Chat Program in C#

chat-room-300x300
chat-room-300x300

Online communication is one feature that the Internet has made possible. It allows faster communication compared to mailing letters which was the only medium that we had in the past centuries to communicate across cities, states, and countries. Through the use of the C# programming language, you will be able to easily make a simple chat program on your laptop. What makes it so easy is because of the built-in methods that C# has that is specifically made for TCP/IP and Socket programming.We will make two objects here, the server and the client. Both of which will have the data algorithms needed for chatting. To start create a new project and name it Chat. Now on the first form, drag a richTextBox object and Lock it in the Parent Container. This will be used to show a transcript of the processes that the server will make. Then double click Form1 and make sure that you are in the Form Load event. Now after you have a block for the Form Load event, add these at the top of the form.


using System.Net;

using System.Net.Sockets;

using System.IO;

These will be where we will get the methods for the server. Next, on the Form Load event create a try-catch block and paste this code on the try block:


  int port = 8000;

                IPAddress ip = IPAddress.Parse("192.168.10.62");

                TcpListener myList= new TcpListener(ip, port);

 

                myList.Start();

      

                Byte[] bytes = new Byte[256];

                String data = null;

 

                // This is the Listening Loop.

                while (true)

                {

                    richTextBox1.AppendText("Waiting for a connection... ");

 

                    Form chat = new Form2();

                    chat.Show();

                    

                    TcpClient client = myList.AcceptTcpClient();

                    richTextBox1.AppendText("Connected!");

 

                    data = null;

                    NetworkStream stream = client.GetStream();

 

                   int i;

                   

                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)

                    {

                        data = Encoding.ASCII.GetString(bytes, 0, i);

                        richTextBox1.AppendText(String.Format("Received: {0}", data));

 

                        data = data.ToUpper();

 

                        Byte[] msg = Encoding.ASCII.GetBytes(data);

 

                        stream.Write(msg, 0, msg.Length);

                        richTextBox1.AppendText(String.Format("Sent: {0}", data));

                    }

                    client.Close();

                }

 

The port represents the specific port socket that the server will receive data from as well as the IP address of the computer. The TcpListener myList is the method that will listen for connection requests and messages from the specific port and computer and we start this through the method myList.Start();. So we also have the other form which is Form2 that we called chat. Now once a connection request is received the server accepts it through the method myList.AcceptTcpClient();.And once it is connected the data that will be received will be converted into ASCII encoding and displayed on the richTextBox1 through appending richTextBox1.Appentext(). Now once the message is received, we will now close the TcpClient client through client.Close(); In the catch block, you can put any error message, for me though I did this


richTextBox1.AppendText("Error..");

Now for the client side, create a new Form and drag in two richTextBox, and one button.

The transcript of the connection and communication will be displayed on the richTextBox1 so make it a little bigger. The richTextBox2 will be where we will be typing the message and the button will be used to send the message. Like on the server side add the following namespaces


using System.Net;

using System.Net.Sockets;

using System.IO;

Now double click the button and like on the server side, you must create a try-catch block and enclose the following in the try block:


  TcpClient tcpclnt = new TcpClient();

                tcpclnt.Connect("192.168.10.62", 8000);

                str = richTextBox2.Text;

                Stream stm = tcpclnt.GetStream();

 

                ASCIIEncoding asen = new ASCIIEncoding();

                byte[] ba = asen.GetBytes(str);

 

                stm.Write(ba, 0, ba.Length);

 

                byte[] bb = new byte[100];

                int k = stm.Read(bb, 0, 100);

 

                for (int i = 0; i <= k; i++)

                {

                    richTextBox1.AppendText(Convert.ToChar(bb[i]).ToString());

                }

                tcpclnt.Close();

              

Now it functions like the server side, just make sure that you use the IP address of the server and the same socket. Lastly on the catch block you can just use the following error code:


richTextBox1.AppendText("Failed sending message!");

You now have a basic client-server chat application. Just add a few more features and you’ll be able to use it effectively for a number of purposes. Whatever you do make sure that the client side will connect to the server once the server side starts listening or else you’ll only be getting the error message.


George