Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Basic C++ TCP Client-Server

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.

Requirements

  • Linux/macOS (POSIX-compliant sockets)
  • C++17 compatible compiler

Compilation

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

Run the program:

Step 1 - Start the server

./server

Server 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 connections

Step 2 - Start the client

Open up an another terminal window and run the client.

./client

If 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)

Step 3 - Send and receive messages

Client will send a harcoded message and server will send it back in the same TCP pipe.

Server Workflow:

  • 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.

Client Workflow:

  • 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

About

TCP Client-Server application using Sockets API

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages