利用套接字来传输文件

Aki 发布于 2023-12-02 294 次阅读


#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

#define PORT 8080 // 可以修改为您希望使用的端口号

int main() {
    int server_fd, new_socket, valread;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    char buffer[1024] = {0};

    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        return 1;
    }

    // 设置套接字选项
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("setsockopt");
        return 1;
    }
    
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // 绑定套接字到指定端口
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        return 1;
    }

    // 监听连接
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        return 1;
    }

    // 等待客户端连接
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
        perror("accept");
        return 1;
    }

    // 打开要传输的文件
    std::ifstream file("file_to_send.txt", std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Unable to open file\n";
        return 1;
    }

    // 读取并发送文件数据
    while (!file.eof()) {
        file.read(buffer, sizeof(buffer));
        send(new_socket, buffer, file.gcount(), 0);
    }

    // 关闭文件和套接字
    file.close();
    close(server_fd);
    return 0;
}
#include<iostream>
#include<fstream>
using namespace std;


int main()
{

	fstream file("libcurl-x64.dll", ios::in | ios::binary);
	fstream new_file("666", ios::out | ios::binary);

	char buffer[2048];
	while (!file.eof())
	{
		file.read(buffer, sizeof(buffer));
		new_file.write(buffer, file.gcount());
	}

	file.close();
	new_file.close();

	return 0;
}