Day 38 tcp

本文介绍了一个使用TCP协议进行文件传输的实例,包括服务器端和客户端的代码实现,展示了如何通过socket编程实现文件在网络间的发送与接收。

TCP 传输文件


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
typedef struct sockaddr * (SA);

int main(int argc, const char *argv[])
{
int listfd = socket(AF_INET, SOCK_STREAM,0);
if(-1 == listfd)
{
perror(“socket”);
exit(1);
}

struct sockaddr_in ser, cli;
ser. sin_family = AF_INET;
ser.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY  127.0.0.1
ser. sin_port = htons(60000);

int len = sizeof(cli);
int ret = bind(listfd, (SA)&ser, sizeof(ser));
if(-1 == ret)
{
    perror("bind");
    exit(1);
}

listen(listfd,3);
int conn =accept(listfd, (SA)&cli, &len);
if(-1 == conn)
{
    perror("accept");
    exit(1);
}

int fd = open("7.jpg", O_RDONLY);
if(-1 == fd)
{
    perror("open");
    exit(1);
}


char buf[1024] = {0};
printf("haha\n");
unsigned int ret1 =recv(conn,buf,1024,0);
printf("%s\n", buf);
printf("hihi\n");

while(1)
{
    ssize_t ret1 = read(fd,buf,1024);
    if(0 ==ret1)
    {
        printf("baibai\n");
        exit(1);
        break;
    }
    send(conn, buf, ret1, 0);
    perror("send");
    printf("%d\n", ret1);
}

close(fd);
close(conn);
close(listfd);
return 0;

}

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> 
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
typedef  struct sockaddr * (SA);

int main(int argc, const char *argv[])
{
    int clifd = socket(AF_INET, SOCK_STREAM,0);
    if(-1 == clifd)
    {
        perror("socket");
        exit(1);
    }

struct sockaddr_in ser, cli;
ser. sin_family = AF_INET;
ser.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY  127.0.0.1
ser. sin_port = htons(60000);

int len = sizeof(cli);



int ret = connect(clifd, (SA)&ser, len);
if(-1 == ret)
{
    perror("accept");
    exit(1);
}

int fd = open("77.jpg", O_RDWR|O_CREAT, 0666);
if(-1 == fd)
{
    perror("open");
    exit(1);
}

char buf[1024] = "server i require iron man picture";
send(clifd, buf, strlen(buf),0);

while(1)
{
    bzero(buf,1024);
    unsigned int ret =recv(clifd,buf,1024,0);
    if(ret <=0)
    {
        break;
    }
    usleep(1000*100);
    ssize_t ret1 = write(fd,buf,  ret);
    printf("%d\n", ret1);
}
close(fd);
close(ret);
close(clifd);
return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值