Linux下多线程文件传输

要求:服务端客户端分辨各占一个进程,客户端中可设置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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值