C++ Socket Programming: TCP Communication Guide
In C++, TCP communication is typically implemented using Socket programming. Below is a simple example code for establishing a TCP connection and sending/receiving data:
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int main() {
// 创建socket
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket < 0) {
std::cerr << "Error creating socket" << std::endl;
return 1;
}
// 设置服务器地址和端口
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(12345);
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
// 连接到服务器
if (connect(client_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
std::cerr << "Error connecting to server" << std::endl;
return 1;
}
// 发送数据
const char *message = "Hello from client!";
if (send(client_socket, message, strlen(message), 0) < 0) {
std::cerr << "Error sending message" << std::endl;
return 1;
}
// 接收数据
char buffer[1024] = {0};
if (recv(client_socket, buffer, 1024, 0) < 0) {
std::cerr << "Error receiving message" << std::endl;
return 1;
}
std::cout << "Server response: " << buffer << std::endl;
// 关闭socket
close(client_socket);
return 0;
}
In this example, we start by creating a client socket, then setting the server address and port. We then connect to the server using the connect function, send a message, receive a response from the server, and finally close the socket.
Please note that this is just a simple example and real-world scenarios may be more complex. In actual applications, you may need to handle errors, timeouts, and packet bundling issues. You can also use third-party libraries such as Boost.Asio to simplify the implementation of TCP communication.