C++socket编程实现文件传输
时间: 2023-09-14 17:14:20 浏览: 183
C++ socket 编程实现文件传输的基本步骤如下:
1. 创建 Socket
使用 `socket()` 函数创建一个套接字,指定通信域、套接字类型和协议类型。例如:
```
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
```
2. 绑定地址
使用 `bind()` 函数将套接字与本地地址绑定。例如:
```
struct sockaddr_in server_addr;
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);
if (bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("bind error");
exit(1);
}
```
3. 监听连接请求
使用 `listen()` 函数监听连接请求。例如:
```
if (listen(sockfd, 10) == -1) {
perror("listen error");
exit(1);
}
```
4. 接受连接请求
使用 `accept()` 函数接受连接请求,创建新的套接字用于数据传输。例如:
```
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int client_sockfd = accept(sockfd, (struct sockaddr*)&client_addr, &client_addr_len);
if (client_sockfd == -1) {
perror("accept error");
exit(1);
}
```
5. 发送文件
使用 `send()` 函数将文件内容发送给客户端。例如:
```
FILE* fp = fopen(filename, "rb");
if (!fp) {
perror("fopen error");
exit(1);
}
char buffer[BUFFER_SIZE];
int nread;
while ((nread = fread(buffer, 1, BUFFER_SIZE, fp)) > 0) {
if (send(client_sockfd, buffer, nread, 0) == -1) {
perror("send error");
exit(1);
}
}
fclose(fp);
```
6. 接收文件
使用 `recv()` 函数接收客户端发送的文件内容。例如:
```
FILE* fp = fopen(filename, "wb");
if (!fp) {
perror("fopen error");
exit(1);
}
char buffer[BUFFER_SIZE];
int nread;
while ((nread = recv(sockfd, buffer, BUFFER_SIZE, 0)) > 0) {
if (fwrite(buffer, 1, nread, fp) != nread) {
perror("fwrite error");
exit(1);
}
}
fclose(fp);
```
完整的示例代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUFFER_SIZE 1024
int main(int argc, char* argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <port> <filename>\n", argv[0]);
exit(1);
}
int port = atoi(argv[1]);
const char* filename = argv[2];
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket error");
exit(1);
}
struct sockaddr_in server_addr;
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);
if (bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("bind error");
exit(1);
}
if (listen(sockfd, 10) == -1) {
perror("listen error");
exit(1);
}
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int client_sockfd = accept(sockfd, (struct sockaddr*)&client_addr, &client_addr_len);
if (client_sockfd == -1) {
perror("accept error");
exit(1);
}
FILE* fp = fopen(filename, "rb");
if (!fp) {
perror("fopen error");
exit(1);
}
char buffer[BUFFER_SIZE];
int nread;
while ((nread = fread(buffer, 1, BUFFER_SIZE, fp)) > 0) {
if (send(client_sockfd, buffer, nread, 0) == -1) {
perror("send error");
exit(1);
}
}
fclose(fp);
close(client_sockfd);
close(sockfd);
return 0;
}
```
阅读全文