How to Build a Simple Chat Application in C#

C# (C-Sharp) code your own application
Thungex

I will show you how to build a simple chat application in C#. This will be a console-based application where users can send messages to each other in real-time. We will use sockets for communication between the server and the clients. By the end of this project, you will have a fully functional chat application that can be expanded further.

Coding image

Chat applications are a great way to learn about networking in programming, especially using sockets. Sockets allow two programs to communicate over a network, making them ideal for chat applications.

Step 1: Setting Up Your Development Environment

Before we start, make sure you have Visual Studio installed. If you do not have it yet, here’s how to get started:

  • Download Visual Studio: Go to the Visual Studio website and download the free Community version.
  • Install Visual Studio: Open the installer and select "Desktop Development with C#."
  • Create a New Console Application Project: Open Visual Studio, click "Create a new project," choose "Console App (.NET Core)," name your project "ChatApp," and click "Create."

Step 2: Understanding Sockets

A socket is one endpoint in a two-way communication link between two programs. In this chat application, we will create two types of sockets:

  • Server Socket: This listens for incoming connections from clients.
  • Client Socket: This connects to the server and communicates by sending and receiving messages.

Both the server and the client will run in the console. The server will handle multiple client connections, allowing them to chat with each other.

Step 3: Building the Server

We will start by building the server that listens for client connections. Follow these steps to create the server:

  1. Open the Program.cs file in your project.
  2. Replace the default code with the following server code:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

class Server
{
    private static TcpListener listener;
    private static int port = 5000;

    static void Main(string[] args)
    {
        listener = new TcpListener(IPAddress.Any, port);
        listener.Start();
        Console.WriteLine("Server started on port " + port);

        while (true)
        {
            TcpClient client = listener.AcceptTcpClient();
            Thread clientThread = new Thread(() => HandleClient(client));
            clientThread.Start();
        }
    }

    private static void HandleClient(TcpClient client)
    {
        NetworkStream stream = client.GetStream();
        byte[] buffer = new byte[1024];
        int bytesRead;

        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received: " + message);

            // Echo the message back to the client
            stream.Write(buffer, 0, bytesRead);
        }

        client.Close();
    }
}

This code sets up a basic server that listens for client connections on port 5000. When a client connects, the server starts a new thread to handle the communication with that client. It listens for incoming messages and echoes them back to the client.

Step 4: Building the Client

Now let’s create the client that will connect to the server and send messages. Follow these steps:

  1. Create a new file in your project called Client.cs.
  2. Copy and paste the following client code:

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

class Client
{
    private static TcpClient client;
    private static NetworkStream stream;

    static void Main(string[] args)
    {
        try
        {
            client = new TcpClient("127.0.0.1", 5000);
            stream = client.GetStream();

            Console.WriteLine("Connected to the server. Type your messages below:");

            Thread receiveThread = new Thread(ReceiveMessages);
            receiveThread.Start();

            while (true)
            {
                string messageToSend = Console.ReadLine();
                byte[] data = Encoding.ASCII.GetBytes(messageToSend);
                stream.Write(data, 0, data.Length);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }

    private static void ReceiveMessages()
    {
        while (true)
        {
            try
            {
                byte[] buffer = new byte[1024];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Server: " + message);
            }
            catch (Exception)
            {
                Console.WriteLine("Disconnected from the server.");
                break;
            }
        }
    }
}

In this code, the client connects to the server using the IP address 127.0.0.1 (which represents localhost). It sends messages to the server and receives messages that the server echoes back. The client continuously reads input from the console and sends it to the server.

Step 5: Running the Application

Here is how you can run and test the application:

  1. Start the Server: Run the server application in Visual Studio (press F5). The server will start and listen for connections.
  2. Start the Client: Open another instance of Visual Studio, create a new Console Application project, and add the Client.cs code. Run the client application. It should connect to the server and allow you to type messages.
  3. Test the Chat Application: Open multiple instances of the client application to simulate different users. Type messages in each client window. You should see the messages appear in the other clients’ windows and on the server console.

In this tutorial, you learned how to create a basic console-based chat application in C# using sockets. You created both the server and client applications, and you tested them by sending messages between clients. This basic chat application can serve as the foundation for more complex projects, such as multi-user chat rooms or messaging apps.

If you want to expand the application further, here are some ideas:

  • Broadcast messages to all clients instead of just echoing them back to the sender.
  • Add usernames for each client and display them with each message.
  • Improve the user interface by building a graphical user interface (GUI) using Windows Forms.

You can copy the code directly from this blog to build your own chat app. Feel free to experiment and add your own features to make it unique.

إرسال تعليق

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.