85 lines
2.3 KiB
C
85 lines
2.3 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
#include <unistd.h>
|
||
|
#include <arpa/inet.h>
|
||
|
|
||
|
#define PORT 8002
|
||
|
#define BUFFER_SIZE 1024
|
||
|
|
||
|
int main() {
|
||
|
int server_socket, client_socket;
|
||
|
struct sockaddr_in server_addr, client_addr;
|
||
|
char buffer[BUFFER_SIZE];
|
||
|
socklen_t client_addr_len = sizeof(client_addr);
|
||
|
|
||
|
// 创建服务器 socket
|
||
|
server_socket = socket(AF_INET, SOCK_STREAM, 0);
|
||
|
if (server_socket == -1) {
|
||
|
perror("服务器 socket 创建失败");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
// 设置 SO_REUSEADDR
|
||
|
int opt = 1;
|
||
|
if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
|
||
|
perror("设置 SO_REUSEADDR 失败");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
// 设置服务器地址
|
||
|
server_addr.sin_family = AF_INET;
|
||
|
server_addr.sin_addr.s_addr = INADDR_ANY;
|
||
|
server_addr.sin_port = htons(PORT);
|
||
|
|
||
|
// 绑定服务器 socket
|
||
|
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
|
||
|
perror("绑定失败");
|
||
|
close(server_socket);
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
// 开始监听
|
||
|
if (listen(server_socket, 5) == -1) {
|
||
|
perror("监听失败");
|
||
|
close(server_socket);
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
printf("服务器已启动,等待客户端连接...\n");
|
||
|
|
||
|
// 接受客户端连接
|
||
|
client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len);
|
||
|
if (client_socket == -1) {
|
||
|
perror("接受客户端连接失败");
|
||
|
close(server_socket);
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
printf("客户端连接成功。\n");
|
||
|
|
||
|
// 打开文件以写入接收到的数据
|
||
|
FILE *file = fopen("received_file.txt", "w");
|
||
|
if (!file) {
|
||
|
perror("文件打开失败");
|
||
|
close(client_socket);
|
||
|
close(server_socket);
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
// 接收分块数据
|
||
|
int bytes_received;
|
||
|
while ((bytes_received = recv(client_socket, buffer, BUFFER_SIZE, 0)) > 0) {
|
||
|
fwrite(buffer, 1, bytes_received, file);
|
||
|
printf("接收到 %d 字节数据。\n", bytes_received);
|
||
|
}
|
||
|
|
||
|
printf("文件接收完成,已保存为 received_file.txt\n");
|
||
|
|
||
|
// 关闭文件和 socket
|
||
|
fclose(file);
|
||
|
close(client_socket);
|
||
|
close(server_socket);
|
||
|
|
||
|
return 0;
|
||
|
}
|