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

被折叠的 条评论
为什么被折叠?



