在 Linux 中,你可以使用 socket 編程進行文件傳輸
服務器端代碼(server.c):
#include <arpa/inet.h>
#include <netinet/in.h>
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include <sys/socket.h>
#include <unistd.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_size;
char buffer[BUFFER_SIZE];
FILE *file;
// 創建 socket
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
perror("socket");
exit(1);
}
// 配置服務器地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
// 綁定 socket
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("bind");
exit(1);
}
// 監聽連接
if (listen(server_fd, 1) == -1) {
perror("listen");
exit(1);
}
// 接受客戶端連接
client_addr_size = sizeof(client_addr);
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_size);
if (client_fd == -1) {
perror("accept");
exit(1);
}
// 打開文件
file = fopen("file.txt", "rb");
if (file == NULL) {
perror("fopen");
exit(1);
}
// 讀取并發送文件內容
while (!feof(file)) {
size_t bytes_read = fread(buffer, 1, BUFFER_SIZE, file);
send(client_fd, buffer, bytes_read, 0);
}
// 關閉文件和 socket
fclose(file);
close(client_fd);
close(server_fd);
return 0;
}
客戶端代碼(client.c):
#include <arpa/inet.h>
#include <netinet/in.h>
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include <sys/socket.h>
#include <unistd.h>
#define SERVER_IP "127.0.0.1"
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int client_fd;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE];
FILE *file;
// 創建 socket
client_fd = socket(AF_INET, SOCK_STREAM, 0);
if (client_fd == -1) {
perror("socket");
exit(1);
}
// 配置服務器地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(PORT);
// 連接服務器
if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("connect");
exit(1);
}
// 打開文件
file = fopen("received_file.txt", "wb");
if (file == NULL) {
perror("fopen");
exit(1);
}
// 接收并寫入文件內容
while (1) {
ssize_t bytes_received = recv(client_fd, buffer, BUFFER_SIZE, 0);
if (bytes_received <= 0) {
break;
}
fwrite(buffer, 1, bytes_received, file);
}
// 關閉文件和 socket
fclose(file);
close(client_fd);
return 0;
}
要編譯和運行這些示例代碼,請按照以下步驟操作:
server.c
和 client.c
。gcc server.c -o server
和 gcc client.c -o client
。./server
。./client
。received_file.txt
。注意:這個示例代碼僅用于演示目的,實際應用中可能需要考慮更多的錯誤處理和優化。