Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

i want to make simple chat app with server and client side. in c++ using windows and…

  1. User

    i want to make simple chat app with server and client side. in c++ using windows and codeblocks. how to do it? i have asio and openssl

  2. Assistant

    Creating a simple chat application with both server and client components in C++ on Windows using Code::Blocks, ASIO, and OpenSSL involves several steps. Below is a comprehensive guide to help you build this application. This guide assumes you have basic knowledge of C++ and networking concepts.

    Overview

    1. Setup Development Environment
    2. Understand ASIO and OpenSSL
    3. Design the Application Architecture
    4. Implement the Server
    5. Implement the Client
    6. Secure Communication with OpenSSL
    7. Testing the Application

    1. Setup Development Environment

    Install Code::Blocks

    If you haven't already, download and install Code::Blocks.

    Install ASIO

    You can use standalone ASIO or Boost.Asio. For simplicity, we'll use standalone ASIO.

    1. Download ASIO:

    2. Include ASIO in Your Project:

      • Extract the ASIO package.
      • In Code::Blocks, go to Project > Build Options > Search directories > Compiler.
      • Add the path to the ASIO include directory.

    Install OpenSSL

    1. Download OpenSSL:

      • Download precompiled OpenSSL binaries for Windows from slproweb.com.
    2. Install OpenSSL:

      • Follow the installation instructions and note the installation path.
    3. Configure Code::Blocks to Use OpenSSL:

      • Go to Project > Build Options > Search directories > Compiler and add the path to OpenSSL's include directory.
      • Go to Project > Build Options > Search directories > Linker and add the path to OpenSSL's lib directory.
      • Under Linker settings, add libssl.lib and libcrypto.lib.

    2. Understand ASIO and OpenSSL

    • ASIO: A cross-platform C++ library for network and low-level I/O programming that provides a consistent asynchronous model.

    • OpenSSL: A robust toolkit for implementing SSL/TLS protocols to secure communications.


    3. Design the Application Architecture

    Server:

    • Listens on a specific port for incoming client connections.
    • Handles multiple clients concurrently.
    • Receives messages from clients and broadcasts them to all connected clients.

    Client:

    • Connects to the server.
    • Sends user input messages to the server.
    • Receives and displays messages broadcasted from the server.

    4. Implement the Server

    Below is a simplified version of a server using ASIO. This example does not include OpenSSL for simplicity. Later, we will discuss how to integrate SSL.

    Server.cpp

    #include <iostream>
    #include <set>
    #include <memory>
    #include <asio.hpp>
    #include <asio/ssl.hpp>
    
    using asio::ip::tcp;
    
    // Forward declaration
    class Session;
    typedef std::shared_ptr<Session> session_ptr;
    
    // The server class
    class Server {
    public:
        Server(asio::io_context& io_context, unsigned short port)
            : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) {
            start_accept();
        }
    
        void broadcast(const std::string& message, session_ptr exclude_session = nullptr) {
            for(auto& session : sessions_) {
                if(session != exclude_session) {
                    session->deliver(message);
                }
            }
        }
    
        void join(session_ptr session) {
            sessions_.insert(session);
        }
    
        void leave(session_ptr session) {
            sessions_.erase(session);
        }
    
    private:
        void start_accept();
    
        tcp::acceptor acceptor_;
        std::set<session_ptr> sessions_;
    };
    
    // The session class
    class Session : public std::enable_shared_from_this<Session> {
    public:
        Session(tcp::socket socket, Server& server)
            : socket_(std::move(socket)), server_(server) {}
    
        void start() {
            server_.join(shared_from_this());
            do_read();
        }
    
        void deliver(const std::string& msg) {
            asio::post(socket_.get_executor(),
                [this, msg]() {
                    bool write_in_progress = !write_msgs_.empty();
                    write_msgs_.push_back(msg);
                    if (!write_in_progress) {
                        do_write();
                    }
                }
            );
        }
    
    private:
        void do_read() {
            auto self(shared_from_this());
            socket_.async_read_some(asio::buffer(data_, max_length),
                [this, self](std::error_code ec, std::size_t length) {
                    if (!ec) {
                        std::string msg(data_, length);
                        server_.broadcast(msg, self);
                        do_read();
                    }
                    else {
                        server_.leave(shared_from_this());
                    }
                }
            );
        }
    
        void do_write() {
            auto self(shared_from_this());
            asio::async_write(socket_,
                asio::buffer(write_msgs_.front().data(), write_msgs_.front().length()),
                [this, self](std::error_code ec, std::size_t /*length*/) {
                    if (!ec) {
                        write_msgs_.pop_front();
                        if (!write_msgs_.empty()) {
                            do_write();
                        }
                    }
                    else {
                        server_.leave(shared_from_this());
                    }
                }
            );
        }
    
        tcp::socket socket_;
        Server& server_;
        enum { max_length = 1024 };
        char data_[max_length];
        std::deque<std::string> write_msgs_;
    };
    
    void Server::start_accept() {
        acceptor_.async_accept(
            [this](std::error_code ec, tcp::socket socket) {
                if (!ec) {
                    std::make_shared<Session>(std::move(socket), *this)->start();
                }
                start_accept();
            }
        );
    }
    
    int main(int argc, char* argv[]) {
        try {
            if (argc !=2 ) {
                std::cerr << "Usage: server <port>\n";
                return 1;
            }
    
            asio::io_context io_context;
            Server server(io_context, std::atoi(argv[1]));
            io_context.run();
        }
        catch(std::exception& e) {
            std::cerr << "Exception: " << e.what() << "\n";
        }
    
        return 0;
    }
    

    Explanation:

    • Server Class:

      • Initializes an acceptor to listen on the specified port.
      • Manages connected sessions.
      • Broadcasts incoming messages to all connected clients except the sender.
    • Session Class:

      • Handles individual client connections.
      • Reads data asynchronously from the client.
      • Sends messages to the client.

    Compile the Server:

    1. Create a new Console Application project in Code::Blocks.
    2. Add the above Server.cpp code to the project.
    3. Make sure to link with ASIO and OpenSSL if necessary (for this basic version, OpenSSL isn't used yet).
    4. Build and run the server by specifying a port number, e.g., 1234.

    5. Implement the Client

    Here's a basic client implementation using ASIO.

    Client.cpp

    #include <iostream>
    #include <thread>
    #include <asio.hpp>
    #include <asio/ssl.hpp>
    
    using asio::ip::tcp;
    
    class Client {
    public:
        Client(asio::io_context& io_context,
               const std::string& host,
               const std::string& port)
            : resolver_(io_context),
              socket_(io_context) {
            do_connect(host, port);
        }
    
        void write(const std::string& msg) {
            asio::post(socket_.get_executor(),
                [this, msg]() {
                    bool write_in_progress = !write_msgs_.empty();
                    write_msgs_.push_back(msg);
                    if (!write_in_progress) {
                        do_write();
                    }
                }
            );
        }
    
        void close() {
            asio::post(socket_.get_executor(), [this]() { socket_.close(); });
        }
    
    private:
        void do_connect(const std::string& host, const std::string& port) {
            auto endpoints = resolver_.resolve(host, port);
            asio::async_connect(socket_, endpoints,
                [this](std::error_code ec, tcp::endpoint) {
                    if (!ec) {
                        do_read();
                    }
                    else {
                        std::cerr << "Connect failed: " << ec.message() << "\n";
                    }
                }
            );
        }
    
        void do_read() {
            socket_.async_read_some(asio::buffer(data_, max_length),
                [this](std::error_code ec, std::size_t length) {
                    if (!ec) {
                        std::cout.write(data_, length);
                        std::cout << "\n";
                        do_read();
                    }
                    else {
                        socket_.close();
                    }
                }
            );
        }
    
        void do_write() {
            asio::async_write(socket_,
                asio::buffer(write_msgs_.front().data(),
                             write_msgs_.front().length()),
                [this](std::error_code ec, std::size_t /*length*/) {
                    if (!ec) {
                        write_msgs_.pop_front();
                        if (!write_msgs_.empty()) {
                            do_write();
                        }
                    }
                    else {
                        socket_.close();
                    }
                }
            );
        }
    
        tcp::resolver resolver_;
        tcp::socket socket_;
        enum { max_length = 1024 };
        char data_[max_length];
        std::deque<std::string> write_msgs_;
    };
    
    int main(int argc, char* argv[]) {
        try {
            if (argc !=3 ) {
                std::cerr << "Usage: client <host> <port>\n";
                return 1;
            }
    
            asio::io_context io_context;
    
            Client c(io_context, argv[1], argv[2]);
    
            std::thread t([&io_context](){ io_context.run(); });
    
            std::string line;
            while (std::getline(std::cin, line)) {
                c.write(line);
            }
    
            c.close();
            t.join();
        }
        catch(std::exception& e) {
            std::cerr << "Exception: " << e.what() << "\n";
        }
    
        return 0;
    }
    

    Explanation:

    • Client Class:
      • Resolves the server address and connects to it.
      • Reads user input from the console and sends it to the server.
      • Receives messages from the server and displays them.

    Compile the Client:

    1. Create another Console Application project in Code::Blocks.
    2. Add the above Client.cpp code to the project.
    3. Ensure ASIO and OpenSSL are correctly linked.
    4. Build and run the client by specifying the server's host and port, e.g., localhost 1234.

    6. Secure Communication with OpenSSL

    To secure the communication between the server and clients using SSL/TLS, you'll need to integrate OpenSSL with ASIO's SSL support.

    Generate SSL Certificates

    For testing purposes, you can generate a self-signed certificate.

    1. Generate a Private Key:

      openssl genrsa -out server.key 2048
      
    2. Generate a Certificate Signing Request (CSR):

      openssl req -new -key server.key -out server.csr
      

      Fill in the required information when prompted.

    3. Generate a Self-Signed Certificate:

      openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
      

      This will create server.crt and server.key.

    Integrate SSL into the Server

    Modify the server to use SSL.

    Server_SSL.cpp

    #include <iostream>
    #include <set>
    #include <memory>
    #include <asio.hpp>
    #include <asio/ssl.hpp>
    
    using asio::ip::tcp;
    
    // Forward declaration
    class Session;
    typedef std::shared_ptr<Session> session_ptr;
    
    // The server class
    class Server {
    public:
        Server(asio::io_context& io_context,
               unsigned short port,
               asio::ssl::context& ssl_context)
            : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)),
              ssl_context_(ssl_context) {
            start_accept();
        }
    
        void broadcast(const std::string& message, session_ptr exclude_session = nullptr) {
            for(auto& session : sessions_) {
                if(session != exclude_session) {
                    session->deliver(message);
                }
            }
        }
    
        void join(session_ptr session) {
            sessions_.insert(session);
        }
    
        void leave(session_ptr session) {
            sessions_.erase(session);
        }
    
    private:
        void start_accept();
    
        tcp::acceptor acceptor_;
        asio::ssl::context& ssl_context_;
        std::set<session_ptr> sessions_;
    };
    
    // The session class
    class Session : public std::enable_shared_from_this<Session> {
    public:
        Session(tcp::socket socket,
                asio::ssl::context& ssl_context,
                Server& server)
            : ssl_stream_(std::move(socket), ssl_context),
              server_(server) {}
    
        void start() {
            server_.join(shared_from_this());
            do_handshake();
        }
    
        void deliver(const std::string& msg) {
            asio::post(ssl_stream_.get_executor(),
                [this, msg]() {
                    bool write_in_progress = !write_msgs_.empty();
                    write_msgs_.push_back(msg);
                    if (!write_in_progress) {
                        do_write();
                    }
                }
            );
        }
    
    private:
        void do_handshake() {
            auto self(shared_from_this());
            ssl_stream_.async_handshake(asio::ssl::stream_base::server,
                [this, self](std::error_code ec) {
                    if (!ec) {
                        do_read();
                    }
                    else {
                        server_.leave(shared_from_this());
                    }
                }
            );
        }
    
        void do_read() {
            auto self(shared_from_this());
            ssl_stream_.async_read_some(asio::buffer(data_, max_length),
                [this, self](std::error_code ec, std::size_t length) {
                    if (!ec) {
                        std::string msg(data_, length);
                        server_.broadcast(msg, self);
                        do_read();
                    }
                    else {
                        server_.leave(shared_from_this());
                    }
                }
            );
        }
    
        void do_write() {
            auto self(shared_from_this());
            asio::async_write(ssl_stream_,
                asio::buffer(write_msgs_.front().data(),
                             write_msgs_.front().length()),
                [this, self](std::error_code ec, std::size_t /*length*/) {
                    if (!ec) {
                        write_msgs_.pop_front();
                        if (!write_msgs_.empty()) {
                            do_write();
                        }
                    }
                    else {
                        server_.leave(shared_from_this());
                    }
                }
            );
        }
    
        asio::ssl::stream<tcp::socket> ssl_stream_;
        Server& server_;
        enum { max_length = 1024 };
        char data_[max_length];
        std::deque<std::string> write_msgs_;
    };
    
    void Server::start_accept() {
        acceptor_.async_accept(
            [this](std::error_code ec, tcp::socket socket) {
                if (!ec) {
                    std::make_shared<Session>(std::move(socket), ssl_context_, *this)->start();
                }
                start_accept();
            }
        );
    }
    
    int main(int argc, char* argv[]) {
        try {
            if (argc !=4 ) {
                std::cerr << "Usage: server_ssl <port> <cert_file> <key_file>\n";
                return 1;
            }
    
            asio::io_context io_context;
    
            asio::ssl::context ssl_context(asio::ssl::context::sslv23);
            ssl_context.set_options(
                asio::ssl::context::default_workarounds
                | asio::ssl::context::no_sslv2
                | asio::ssl::context::single_dh_use);
            ssl_context.use_certificate_chain_file(argv[2]);
            ssl_context.use_private_key_file(argv[3], asio::ssl::context::pem);
    
            Server server(io_context, std::atoi(argv[1]), ssl_context);
            io_context.run();
        }
        catch(std::exception& e) {
            std::cerr << "Exception: " << e.what() << "\n";
        }
    
        return 0;
    }
    

    Explanation:

    • SSL Context:

      • Initialized with the server's certificate and private key.
    • Session Class:

      • Uses asio::ssl::stream to handle encrypted communication.
      • Performs SSL handshake upon connection.

    Integrate SSL in Client

    Modify the client to use SSL.

    Client_SSL.cpp

    #include <iostream>
    #include <thread>
    #include <asio.hpp>
    #include <asio/ssl.hpp>
    
    using asio::ip::tcp;
    
    class Client {
    public:
        Client(asio::io_context& io_context,
               asio::ssl::context& ssl_context,
               const std::string& host,
               const std::string& port)
            : resolver_(io_context),
              ssl_stream_(io_context, ssl_context) {
            do_resolve(host, port);
        }
    
        void write(const std::string& msg) {
            asio::post(ssl_stream_.get_executor(),
                [this, msg]() {
                    bool write_in_progress = !write_msgs_.empty();
                    write_msgs_.push_back(msg);
                    if (!write_in_progress) {
                        do_write();
                    }
                }
            );
        }
    
        void close() {
            asio::post(ssl_stream_.get_executor(),
                [this]() {
                    ssl_stream_.lowest_layer().close();
                }
            );
        }
    
    private:
        void do_resolve(const std::string& host, const std::string& port) {
            auto endpoints = resolver_.resolve(host, port);
            asio::async_connect(ssl_stream_.lowest_layer(), endpoints,
                [this](std::error_code ec, tcp::endpoint) {
                    if (!ec) {
                        do_handshake();
                    }
                    else {
                        std::cerr << "Connect failed: " << ec.message() << "\n";
                    }
                }
            );
        }
    
        void do_handshake() {
            ssl_stream_.async_handshake(asio::ssl::stream_base::client,
                [this](std::error_code ec) {
                    if (!ec) {
                        do_read();
                    }
                    else {
                        std::cerr << "Handshake failed: " << ec.message() << "\n";
                        ssl_stream_.lowest_layer().close();
                    }
                }
            );
        }
    
        void do_read() {
            ssl_stream_.async_read_some(asio::buffer(data_, max_length),
                [this](std::error_code ec, std::size_t length) {
                    if (!ec) {
                        std::cout.write(data_, length);
                        std::cout << "\n";
                        do_read();
                    }
                    else {
                        ssl_stream_.lowest_layer().close();
                    }
                }
            );
        }
    
        void do_write() {
            asio::async_write(ssl_stream_,
                asio::buffer(write_msgs_.front().data(),
                             write_msgs_.front().length()),
                [this](std::error_code ec, std::size_t /*length*/) {
                    if (!ec) {
                        write_msgs_.pop_front();
                        if (!write_msgs_.empty()) {
                            do_write();
                        }
                    }
                    else {
                        ssl_stream_.lowest_layer().close();
                    }
                }
            );
        }
    
        tcp::resolver resolver_;
        asio::ssl::stream<tcp::socket> ssl_stream_;
        enum { max_length = 1024 };
        char data_[max_length];
        std::deque<std::string> write_msgs_;
    };
    
    int main(int argc, char* argv[]) {
        try {
            if (argc !=4 ) {
                std::cerr << "Usage: client_ssl <host> <port> <ca_cert>\n";
                return 1;
            }
    
            asio::io_context io_context;
    
            asio::ssl::context ssl_context(asio::ssl::context::sslv23);
            ssl_context.load_verify_file(argv[3]);
            ssl_context.set_verify_mode(asio::ssl::verify_peer);
    
            Client c(io_context, ssl_context, argv[1], argv[2]);
    
            std::thread t([&io_context](){ io_context.run(); });
    
            std::string line;
            while (std::getline(std::cin, line)) {
                c.write(line);
            }
    
            c.close();
            t.join();
        }
        catch(std::exception& e) {
            std::cerr << "Exception: " << e.what() << "\n";
        }
    
        return 0;
    }
    

    Explanation:

    • SSL Context:

      • Configured for client verification.
      • Loads the CA certificate to verify the server's certificate.
    • Client Class:

      • Uses asio::ssl::stream for encrypted communication.
      • Performs SSL handshake after establishing a TCP connection.

    Compile the SSL Versions:

    1. Create separate projects or add these as additional source files.

    2. Ensure you provide the correct command-line arguments:

      • For the server: server_ssl <port> <cert_file> <key_file>
      • For the client: client_ssl <host> <port> <ca_cert>
    3. Build and run the server and client with SSL enabled.

    Note: For a production environment, you should obtain certificates from a trusted Certificate Authority (CA).


    7. Testing the Application

    1. Run the Server:

      server_ssl 1234 server.crt server.key
      
    2. Run Multiple Clients:

      client_ssl localhost 1234 server.crt
      
    3. Chat:

      • Type messages in any client window.
      • Messages should appear in all connected clients' windows.

    Additional Tips

    • Error Handling: Enhance error handling to manage disconnects and other network issues gracefully.

    • User Identification: Implement a way for users to identify themselves, such as sending a username upon connecting.

    • GUI Interface: For a more user-friendly experience, consider integrating a GUI library like Qt or wxWidgets.

    • Multithreading: ASIO is asynchronous, but ensure that any shared resources are thread-safe if you expand functionality.


    Resources


    By following this guide, you should be able to create a basic secure chat application using C++, ASIO, and OpenSSL on Windows with Code::Blocks. As you become more comfortable, consider adding more features such as authentication, message history, and a graphical user interface.