怎样用c语言实现服务器向客户端发送一个文件
时间: 2024-02-03 13:02:48 浏览: 36
以下是一个基本的C语言程序,用于将服务器上的文件发送到客户端:
```
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[]) {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";
FILE *file;
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Attaching socket to the port 8080
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);
// Binding the socket to the specified port
if (bind(server_fd, (struct sockaddr *) &address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Listening for incoming connections
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
// Accepting incoming connection
if ((new_socket = accept(server_fd, (struct sockaddr *) &address,
(socklen_t *) &addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// Opening the file to be sent
file = fopen("file.txt", "r");
if (file == NULL) {
perror("file open failed");
exit(EXIT_FAILURE);
}
// Sending the file to the client
while (fgets(buffer, 1024, file) != NULL) {
send(new_socket, buffer, strlen(buffer), 0);
memset(buffer, 0, sizeof(buffer));
}
// Closing the file and the socket connection
fclose(file);
close(new_socket);
close(server_fd);
return 0;
}
```
该程序使用了一个基本的Socket编程来实现服务器向客户端发送文件。程序首先创建一个Socket文件描述符,然后将其绑定到指定的端口。然后,它侦听传入的连接,接受传入的连接并打开要发送的文件。程序使用fgets函数从文件中读取数据,并使用send函数将数据发送到客户端。最后,程序关闭文件和Socket连接。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)