C++ 基于tcp协议的socket通信
时间: 2023-10-10 21:11:40 浏览: 44
C++ 基于tcp协议的socket通信需要使用socket编程库,可以使用标准的BSD socket API 或者是跨平台的Boost.Asio库。
下面是一个使用BSD socket API实现的简单的客户端和服务器端代码示例:
服务器端代码:
```c++
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
int main() {
// 创建socket
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
cout << "Failed to create socket!" << endl;
return -1;
}
// 绑定地址和端口号
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8888);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) == -1) {
cout << "Failed to bind socket!" << endl;
return -1;
}
// 监听连接
if (listen(server_fd, 5) == -1) {
cout << "Failed to listen socket!" << endl;
return -1;
}
// 等待连接
int client_fd;
struct sockaddr_in client_addr;
socklen_t addr_len = sizeof(client_addr);
if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addr_len)) == -1) {
cout << "Failed to accept connection!" << endl;
return -1;
}
// 读取数据
char buffer[1024] = {0};
int read_len;
if ((read_len = read(client_fd, buffer, 1024)) == -1) {
cout << "Failed to read data!" << endl;
return -1;
}
cout << "Received message: " << buffer << endl;
// 发送数据
const char *response = "Hello World!";
if (write(client_fd, response, strlen(response)) == -1) {
cout << "Failed to send data!" << endl;
return -1;
}
// 关闭连接
close(client_fd);
close(server_fd);
return 0;
}
```
客户端代码:
```c++
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
int main() {
// 创建socket
int client_fd = socket(AF_INET, SOCK_STREAM, 0);
if (client_fd == -1) {
cout << "Failed to create socket!" << endl;
return -1;
}
// 连接服务器
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0) {
cout << "Invalid address or address not supported!" << endl;
return -1;
}
if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
cout << "Failed to connect server!" << endl;
return -1;
}
// 发送数据
const char *message = "Hello Server!";
if (write(client_fd, message, strlen(message)) == -1) {
cout << "Failed to send data!" << endl;
return -1;
}
// 读取数据
char buffer[1024] = {0};
int read_len;
if ((read_len = read(client_fd, buffer, 1024)) == -1) {
cout << "Failed to read data!" << endl;
return -1;
}
cout << "Received message: " << buffer << endl;
// 关闭连接
close(client_fd);
return 0;
}
```