Client Server programming in C# (Chat application)

C# simplifies the network programming through its namespaces like System.Net and System.Net.Sockets. A Socket is an End-Point of To and From (Bidirectional) communication link between two programs (Server Program and Client Program ) running on the same network . We need two programs for communicating a socket application in C#. A Server Socket Program ( Server ) and a Client Socket Program ( Client ).
So let's develop a Client Server Windows Forms C# application (chat application). First let's create this Windows Form:


TextBoxes names : ServerIPtextBox, ServerPorttextBox, ClientIPtextBox, ClientPorttextBox, ChatScreentextBox, MessagetextBox.
Then add two BackgroundWorker to the project.
And add these namespaces to the project:

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

After that, declare these variables:

private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string recieve;
public String TextToSend;


And add this code in Form1():

public Form1()
{
    InitializeComponent();

    IPAddress[] localIP= Dns.GetHostAddresses(Dns.GetHostName());

    foreach(IPAddress address in localIP)
    {
        if(address.AddressFamily == AddressFamily.InterNetwork)
        {
            ServerIPtextBox.Text = address.ToString();
        }
    }

}

In StartButton click event add this code:

private void StartButton_Click(object sender, EventArgs e)
{
    TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(ServerPorttextBox.Text));
    listener.Start();
    client = listener.AcceptTcpClient();
    STR = new StreamReader(client.GetStream());
    STW = new StreamWriter(client.GetStream());
    STW.AutoFlush = true;

    backgroundWorker1.RunWorkerAsync();
    backgroundWorker2.WorkerSupportsCancellation = true;

}

In ConnectButton click event add this code:

private void ConnectButton_Click(object sender, EventArgs e)
{
    client = new TcpClient();
    IPEndPoint IpEnd = new IPEndPoint(IPAddress.Parse(ClientIPtextBox.Text), int.Parse(ClientPorttextBox.Text));

    try
    {
        client.Connect(IpEnd);

        if(client.Connected)
        {
            ChatScreentextBox.AppendText("Connected to server" + "\n");
            STW = new StreamWriter(client.GetStream());
            STR = new StreamReader(client.GetStream());
            STW.AutoFlush = true;
            backgroundWorker1.RunWorkerAsync();
            backgroundWorker2.WorkerSupportsCancellation = true;

        }
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
}

In backgroundWorker1 DoWork event add this code:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    while(client.Connected)
    {
        try
        {
            recieve = STR.ReadLine();
            this.ChatScreentextBox.Invoke(new MethodInvoker(delegate()
                {
                    ChatScreentextBox.AppendText("You:" + recieve + "\n");
                }));
            recieve = "";
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }
    }
}

And in backgroundWorker2 DoWork event add this code:

private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
    if(client.Connected)
    {
        STW.WriteLine(TextToSend);
        this.ChatScreentextBox.Invoke(new MethodInvoker(delegate()
        {
            ChatScreentextBox.AppendText("Me:" + TextToSend + "\n");
        }));
    }
    else
    {
        MessageBox.Show("Sending failed");
    }
    backgroundWorker2.CancelAsync();
}

Finally in SendButton click event add this code:

private void SendButton_Click(object sender, EventArgs e)
{
    if(MessagetextBox.Text!="")
    {
        TextToSend = MessagetextBox.Text;
        backgroundWorker2.RunWorkerAsync();
    }
    MessagetextBox.Text = "";

}

Then let's run the application and open a second instance to it from (%project directory%\bin\Debug). Open two instances for testing purposes in your computer, then give the IP address and Port number to the two instances. Then connect both Applications and start sending messages.

Check this video for more explanation:




Client Server programming in C# (Chat application) Client Server programming in C# (Chat application) Reviewed by Bloggeur DZ on 08:14 Rating: 5

14 commentaires:

  1. Thanks a lot! I'm am having problem in stopping the server and also in disconnecting the client. Can you send me the code for both situations. Thanks in advance.

    RépondreSupprimer
  2. it is giving an error . can u help me with that ASAP

    RépondreSupprimer
  3. hello,
    I have a problem, when i press the "START" button, my application crashes. Anyone have any clue of what's going on ?
    Thanks in advance! :-)

    RépondreSupprimer
  4. How Can I run this client application in one pc and server application in other PC of this example?

    RépondreSupprimer
  5. Can verify this still works great at start of 2019.
    Do note this is done in windows forms and not WPF.

    Thanks for the tut and good luck to all.

    RépondreSupprimer
  6. Thank you for the code. Very succinct. Worked great!

    RépondreSupprimer
  7. Hi, how to write these lines in wpf ? this.ChatScreentextBox.Invoke(new MethodInvoker(delegate()
    {
    ChatScreentextBox.AppendText("Me:" + TextToSend + "\n");
    }));

    RépondreSupprimer
  8. I am getting error on the IP line. It says string is not in correct form.

    TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(ServerPorttextBox.Text));

    RépondreSupprimer
  9. PLEASE RESPOND: I have an error for every "MessageBox.Show(ex.Message.ToString());" and I don't know why...

    RépondreSupprimer
  10. it was a wonderful chance to visit this kind of site and I am happy to know. thank you so much for giving us a chance to have this opportunity.. free tango download

    RépondreSupprimer

Fourni par Blogger.