用C++实现一个数据传输
时间: 2024-05-04 13:19:40 浏览: 75
要实现数据传输,可以使用C++的网络编程库。下面是一个简单的例子,使用socket进行数据传输:
服务端代码:
```cpp
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
int main(int argc, char const *argv[])
{
// 创建socket
int server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server_socket == -1)
{
cerr << "Create socket failed!" << endl;
return -1;
}
// 绑定IP和端口号
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(8888);
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
{
cerr << "Bind failed!" << endl;
close(server_socket);
return -1;
}
// 监听
if (listen(server_socket, 20) == -1)
{
cerr << "Listen failed!" << endl;
close(server_socket);
return -1;
}
cout << "Server is listening..." << endl;
// 接收连接请求
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len);
if (client_socket == -1)
{
cerr << "Accept failed!" << endl;
close(server_socket);
return -1;
}
cout << "Connection established!" << endl;
// 发送数据
char message[] = "Hello, client!";
if (send(client_socket, message, strlen(message), 0) == -1)
{
cerr << "Send failed!" << endl;
close(client_socket);
close(server_socket);
return -1;
}
// 关闭连接
close(client_socket);
close(server_socket);
return 0;
}
```
客户端代码:
```cpp
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
int main(int argc, char const *argv[])
{
// 创建socket
int client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (client_socket == -1)
{
cerr << "Create socket failed!" << endl;
return -1;
}
// 连接服务器
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(8888);
if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
{
cerr << "Connect failed!" << endl;
close(client_socket);
return -1;
}
// 接收数据
char buffer[1024] = {0};
if (recv(client_socket, buffer, sizeof(buffer), 0) == -1)
{
cerr << "Receive failed!" << endl;
close(client_socket);
return -1;
}
cout << "Server says: " << buffer << endl;
// 关闭连接
close(client_socket);
return 0;
}
```
在这个例子中,服务端创建了一个socket,并绑定了IP和端口号,然后开始监听客户端连接请求。客户端创建了一个socket,并连接到服务端指定的IP和端口号。连接成功后,客户端向服务端发送数据,服务端接收到数据后,向客户端回复数据。最后客户端和服务端关闭连接。
这只是一个简单的例子,实际应用中需要考虑更多的问题,如数据包的大小,传输速度,错误处理等。
阅读全文