Mark As Completed Discussion

To build a TCP client in C++, you can follow these steps:

  1. Create a socket using the socket() function. Specify the address family, socket type, and protocol.

    TEXT/X-C++SRC
    1int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    2if (sockfd == -1) {
    3  std::cout << "Failed to create socket" << std::endl;
    4  return 1;
    5}
  2. Connect to the server using the connect() function. Specify the server address and port in a sockaddr_in structure.

    TEXT/X-C++SRC
    1struct sockaddr_in serverAddr;
    2serverAddr.sin_family = AF_INET;
    3serverAddr.sin_port = htons(8080);
    4serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    5
    6if (connect(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) {
    7  std::cout << "Failed to connect to server" << std::endl;
    8  return 1;
    9}
  3. Send and receive data on the client socket using the write() and read() functions.

    TEXT/X-C++SRC
    1const char* message = "Hello from the client!";
    2write(sockfd, message, strlen(message));
    3
    4char buffer[1024] = {0};
    5read(sockfd, buffer, 1024);
    6std::cout << "Received message: " << buffer << std::endl;
  4. Close the socket using the close() function.

    TEXT/X-C++SRC
    1close(sockfd);

Here's an example code that demonstrates how to build a TCP client in C++:

TEXT/X-C++SRC
1#include <iostream>
2#include <sys/socket.h>
3#include <netinet/in.h>
4#include <unistd.h>
5#include <cstring>
6
7int main() {
8  // Create a socket
9  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
10  if (sockfd == -1) {
11    std::cout << "Failed to create socket" << std::endl;
12    return 1;
13  }
14
15  // Connect to the server
16  struct sockaddr_in serverAddr;
17  serverAddr.sin_family = AF_INET;
18  serverAddr.sin_port = htons(8080);
19  serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
20
21  if (connect(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) {
22    std::cout << "Failed to connect to server" << std::endl;
23    return 1;
24  }
25
26  // Send and receive data
27  const char* message = "Hello from the client!";
28  write(sockfd, message, strlen(message));
29
30  char buffer[1024] = {0};
31  read(sockfd, buffer, 1024);
32  std::cout << "Received message: " << buffer << std::endl;
33
34  // Close the socket
35  close(sockfd);
36
37  return 0;
38}