Network Chat Application Gaming Project in C++

Server Code:

Client Code:

Explanation:

Server Code:

  1. Setup:
    • Creates a socket using socket().
    • Configures server address serverAddr with AF_INET (IPv4), INADDR_ANY (binds to all available interfaces), and PORT.
    • Binds the socket to the address using bind().
    • Listens for incoming connections with listen().
  2. Handling Clients:
    • Uses accept() to accept incoming client connections.
    • Spawns a new thread to handle each client connection. The handleClient() function:
      • Receives messages from the client.
      • Prints the received message.
      • Sends the same message back to the client (echo server).
    • Closes the client socket when done.
  3. Error Handling:
    • Checks for errors at each step and prints appropriate error messages using perror().

Client Code:

  1. Setup:
    • Creates a socket with socket().
    • Configures server address serv_addr with AF_INET and PORT.
    • Converts IP address to binary form with inet_pton() and connects to the server using connect().
  2. Interaction:
    • Sends user input to the server with send().
    • Receives and prints the server’s response with recv().
    • Exits the loop if the user types “exit”.
  3. Error Handling:
    • Checks for connection errors and displays messages if needed.

      How to Run:

      Compile and Run the Server:

      Compile and Run the Client:

      Testing:

      • Start the server first.
      • Then, run the client.
      • Type messages in the client and observe that they are echoed back by the server.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top