服务器端代码(接收文件)
服务器端将监听一个端口,等待客户端的连接,并接收客户端发送的文件。
复制代码#include
#include
#include
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#define PORT 8080
#define BUFFER_SIZE 4096
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
std::ofstream outfile(“received_file”, std::ios::binary);
// 创建套接字
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置套接字选项
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
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");
exit(EXIT_FAILURE);
}
// 监听端口
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
// 接受客户端连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// 接收文件数据并写入文件
int bytes_read;
while ((bytes_read = read(new_socket, buffer, BUFFER_SIZE)) > 0) {
outfile.write(buffer, bytes_read);
}
std::cout << "File received successfully.\n";
// 关闭套接字和文件
outfile.close();
close(new_socket);
close(server_fd);
return 0;
}
客户端代码(发送文件)
客户端将连接到服务器端的IP地址和端口,并发送一个文件。
复制代码#include
#include
#include
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
#define BUFFER_SIZE 4096
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
char buffer[BUFFER_SIZE] = {0};
std::ifstream infile(“file_to_send”, std::ios::binary);
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
std::cerr << "\n Socket creation error \n";
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// 将IPv4地址从文本转换为二进制形式
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
std::cerr << "\nInvalid address/ Address not supported \n";
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
std::cerr << "\nConnection Failed \n";
return -1;
}
// 读取文件并发送
while (infile.read(buffer, BUFFER_SIZE)) {
send(sock, buffer, infile.gcount(), 0);
}
// 发送文件的最后一部分(如果有)
if (infile.gcount() > 0) {
send(sock, buffer, infile.gcount(), 0);
}
std::cout << "File sent successfully.\n";
// 关闭套接字和文件
infile.close();
close(sock);
return 0;
}
注意:
这些示例代码假设服务器和客户端都在同一网络中,并且客户端知道服务器的IP地址。
在实际部署时,你需要将客户端代码中的"127.0.0.1"替换为服务器的实际IP地址。
这些代码示例仅用于教学目的,实际应用中可能需要更多的错误处理和安全措施。