linux/test/client.c
2024-12-18 17:24:29 +08:00

80 lines
2.1 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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 client_socket;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE];
char filename[100];
// 创建客户端 socket
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket == -1) {
perror("客户端 socket 创建失败");
exit(EXIT_FAILURE);
}
// 设置服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
// 连接到服务器
if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("连接服务器失败");
close(client_socket);
exit(EXIT_FAILURE);
}
printf("连接服务器成功!\n");
// 输入文件名并创建文件
printf("请输入要创建的文件名(例如 output.txt");
fgets(filename, sizeof(filename), stdin);
filename[strcspn(filename, "\n")] = 0; // 去掉换行符
FILE *file = fopen(filename, "w");
if (!file) {
perror("文件创建失败");
close(client_socket);
exit(EXIT_FAILURE);
}
printf("请输入文件内容,输入 EOF 表示结束:\n");
while (fgets(buffer, sizeof(buffer), stdin)) {
if (strcmp(buffer, "EOF\n") == 0) {
break;
}
fputs(buffer, file);
}
fclose(file);
// 重新打开文件以读取并发送给服务器
file = fopen(filename, "r");
if (!file) {
perror("文件打开失败");
close(client_socket);
exit(EXIT_FAILURE);
}
// 分块发送文件内容
int bytes_read;
while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, file)) > 0) {
send(client_socket, buffer, bytes_read, 0);
printf("发送 %d 字节数据。\n", bytes_read);
}
printf("文件内容已发送到服务器。\n");
// 关闭文件和 socket
fclose(file);
close(client_socket);
return 0;
}