C++ tcp client server example
In order to implement a TCP client-server application in C++, you will need to have a basic understanding of the following concepts:
- Network programming: This involves understanding how to create and use sockets, which are the basic building blocks of network communication.
- The TCP/IP protocol stack: This is the protocol that is used to transmit data over the Internet. Understanding the different layers of the stack and how they work together is important for understanding how network communication works.
- The C++ Standard Template Library (STL): The STL provides a number of useful classes and functions for working with data, including strings and containers.
- C++11 or later: The example code I provided uses some features that were introduced in C++11, such as nullptr, auto, and memset function. So it's important to have knowledge of at least C++11.
- The header files: <sys/types.h>, <sys/socket.h>, <netinet/in.h>, <unistd.h>, <arpa/inet.h> are needed to be included in the project.
- The socket functions: socket(), bind(), listen(), accept(), read(), write() functions.
Additionally, it's also good to be familiar with the UNIX/Linux operating system, as the example code uses some system calls and libraries that are specific to that platform.
Example
Here is an example of a basic TCP client-server implementation in C++:
Server:
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
int main() {
int sockfd, newsockfd, portno;
socklen_tclilen;
char buffer[256];
struct sockaddr_inserv_addr, cli_addr;
int n;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd< 0){
cerr<< "Error creating socket" <<endl;
return 1; }
// Clear address structure
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 5001;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
// Bind the socket to a specific address and port
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
cerr<< "Error binding socket" <<endl;
return 1;}
// Listen for incoming connections
listen(sockfd,5);
clilen = sizeof(cli_addr);
// Accept an incoming connection
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd< 0) {
cerr<< "Error accepting connection" <<endl;
return 1 }
cout<< "Received message: " << buffer <<endl;
// Write data to the client
n = write(newsockfd,"I got your message",18);
if (n < 0)
{
cerr<< "Error writing to socket" <<endl;
return 1;
}
close(newsockfd);
close(sockfd);
return 0;
}
Client
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
int main() {
int sockfd;
struct sockaddr_inserv_addr;
char buffer[256];
int n;
int main() {
int sockfd;
struct sockaddr_inserv_addr;
char buffer[256];
int n;
// Create a socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd< 0) {
cerr<< "Error creating socket" <<endl;
return 1;
}
// Clear address structure
memset((char *) &serv_addr, 0, sizeof(serv_addr));
// Set up the server address
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr);
// Connect to the server
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
cerr<< "Error connecting to server" <<endl;
return 1;
}
// Send data to the server
strcpy(buffer, "Hello, Server!");
n = write(sockfd, buffer, strlen(buffer));
if (n < 0) {
cerr<< "Error writing to socket" <<endl;
return 1;
}
// Read data from the server
memset(buffer, 0, 256);
n = read(sockfd, buffer, 255);
if (n < 0) {
cerr<< "Error reading from socket" <<endl;
return 1;
}
cout<< "Received message: " << buffer <<endl;
close(sockfd);
return 0;
}
Advantages:
There are several advantages to using TCP-based client-server architecture in C++:
- Reliability: TCP is a reliable protocol, which means that data is guaranteed to be delivered to the recipient in the order it was sent. This is important for applications where data integrity is critical.
- Flow control: TCP uses flow control mechanisms to ensure that the sender does not overwhelm the receiver with too much data. This helps to prevent network congestion and ensures that the network is used efficiently
- Error handling: TCP has built-in error handling mechanisms, such as retransmission of lost packets, which helps to ensure that data is delivered accurately.
- Portability: C++ is a portable programming language, which means that the same code can be used on different platforms and architectures. This makes it easy to write client-server applications that can run on a wide range of devices.
- Scalability: The client-server architecture is inherently scalable, as new clients can be added to the system without affecting existing clients or the server.
- Concurrent: The client-server architecture allows for concurrent execution, which means that multiple clients can connect to the server at the same time and receive services simultaneously.
- Security: The protocol is secure and encrypts the data sent over the network, which helps to protect sensitive information from unauthorized access.
- Interoperability: The protocol is widely adopted and supported by various operating systems, which allows for easy communication between different systems and platforms.