This project demonstrates a simple TCP Client-Server architecture in C++ implemented using the Berkeley Sockets API.
- The Server accepts a connection from a client, receives messages, and echoes them back.
- The Client connects to the server, sends messages, and displays the server's response.
- Linux/macOS (POSIX-compliant sockets)
- C++17 compatible compiler
Open a terminal in the project directory and run:
g++ -std=c++17 -Wall -Wextra -O0 -g server.cpp -o server
g++ -std=c++17 -Wall -Wextra -O0 -g client.cpp -o client./serverServer will start listening for incoming TCP connections on 127.0.0.1:8080 Network host and Port has been hardcoded in server.cpp for ease of use.
You should see:
Socket Created, fd: (some file descriptor number)
Socket bound to port 8080
Socket listening for connectionsOpen up an another terminal window and run the client.
./clientIf connection succeeds, then on the server terminal window you should see:
Client connected from 127.0.0.1:51163, fd = (some file descriptor number for client)Client will send a harcoded message and server will send it back in the same TCP pipe.- Create socket – Use socket(AF_INET, SOCK_STREAM, 0) to create a TCP socket.
- Bind – Bind the socket to an IP address (127.0.0.1) and port (e.g., 8080).
- Listen – Mark the socket as a listening socket using listen().
- Accept – Wait for a client connection using accept().
- Communicate - Send and receive messages.
- Close connection – Close the client socket when finished.
- Shutdown server – Stop the server and close its listening socket.
- Create socket – Use socket(AF_INET, SOCK_STREAM, 0) to create a TCP socket.
- Connect – Connect to the server’s IP and port using connect().
- Send message – Write data to the socket using send().
- Receive reply – Wait for the echoed data from the server using recv().
- Display response – Print the echoed message to the terminal.
- Close socket – Disconnect from the server when done