用c plus plus 实现文件传输
时间: 2023-05-19 16:03:47 浏览: 148
文件传输可以通过使用套接字(Socket)来实现,下面是一个使用C++语言编写的简单的文件传输示例代码:
发送端代码:
```cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
const int PORT = 8888; // 端口号
const string IP_ADDRESS = "127.0.0.1"; // IP地址
const int BUFFER_SIZE = 1024; // 缓冲区大小
int main() {
// 创建套接字
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
cerr << "Failed to create socket" << endl;
return -1;
}
// 绑定IP地址和端口号
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = inet_addr(IP_ADDRESS.c_str());
if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
cerr << "Failed to bind socket" << endl;
return -1;
}
// 监听端口
if (listen(sock, 5) < 0) {
cerr << "Failed to listen on socket" << endl;
return -1;
}
// 等待客户端连接
struct sockaddr_in clientAddr;
socklen_t clientAddrLen = sizeof(clientAddr);
int clientSock = accept(sock, (struct sockaddr*)&clientAddr, &clientAddrLen);
if (clientSock < 0) {
cerr << "Failed to accept connection" << endl;
return -1;
}
// 读取文件内容并发送
string filename = "test.txt";
ifstream file(filename.c_str(), ios::binary);
if (!file) {
cerr << "Failed to open file" << endl;
return -1;
}
char buffer[BUFFER_SIZE];
while (file.good()) {
file.read(buffer, BUFFER_SIZE);
int count = file.gcount();
send(clientSock, buffer, count, 0);
}
file.close();
// 关闭套接字
close(clientSock);
close(sock);
return 0;
}
```
接收端代码:
```cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
const int PORT = 8888; // 端口号
const string IP_ADDRESS = "127.0.0.1"; // IP地址
const int BUFFER_SIZE = 1024; // 缓冲区大小
int main() {
// 创建套接字
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
cerr << "Failed to create socket" << endl;
return -1;
}
// 连接到服务器
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS.c_str());
if (connect(sock, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
cerr << "Failed to connect to server" << endl;
阅读全文