要求:服务端客户端分辨各占一个进程,客户端中可设置TCP连接数n,之后将文件等分成n块同时传输。
思路: 在网上查到了许多关于Linux下socket文件传输的文章,受益许多,其中有个博客写的很好
链接:http://blog.csdn.net/zhqianpeng/article/details/46489959
于是可以在客户端中根据n进行文件分包,之后创建n个线程传输,服务端创建相应n个线程完成接收。
客户端代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#define SERV_PORT 8888
#define BUFFER_SIZE 4096
typedef struct
{
long long cur;
int size;
}thread_data;
int filefd;
int file_block_size = 0;
struct sockaddr_in server_address;
void *sender(void *s)
{
thread_data tdata = *((thread_data*)s);
long long cur = tdata.cur;
int size = tdata.size;
char buf[BUFFER_SIZE] = {
0};
int read_count;
char head_buf[29] = {
0};
snprintf(head_buf,29,"%016lld:%011d",cur,size);
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("socket error");
exit(EXIT_SUCCESS);
}
if (connect(sockfd, (struct sockaddr*)&server_address, sizeof(server_address)) < 0)
{
exit(EXIT_FAILURE);
}
send(sockfd, &head_buf, strlen(head_buf), 0);
long long read_size = 0;
while (size)
{
read_count = pread(filefd, buf,(sizeof(buf) < size)?sizeof(buf):size, cur + read_size);
if (read_count < 0 && errno == EINTR)
{ //pread 是原子操作
puts("break by signal");
continue;
}
else if (read_count == 0)
{
break;
}
else if(read_count < 0)
{
perror("pread"); exit(1);
}
send(so