//服务器端:
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
using namespace std;
char* file_path;
char file_name[100];
void* send_file(void* arg);
int main(int argc,char** argv)
{
if(argc!=2)
{
fprintf(stderr,"命令语法错误!\n");
exit(1);
}
if(0!=access(argv[1],R_OK))
{
fprintf(stderr,"待发送的文件不存在或不可读!\n");
exit(1);
}
file_path=argv[1];
char* p=strrchr(argv[1],'/');
if(p==NULL)
{
strcpy(file_name,argv[1]);
}
else
{
strcpy(file_name,p+1);
}
int sock_listen=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in srv_addr;
srv_addr.sin_family=AF_INET;
srv_addr.sin_addr.s_addr=INADDR_ANY;
srv_addr.sin_port=htons(6666);
if(-1==bind(sock_listen,(struct sockaddr*)&srv_addr,sizeof(srv_addr)))
{
perror("bind");
exit(1);
}
listen(sock_listen,5);
int sock_conn;
pthread_t tid;
while(1)
{
sock_conn=accept(sock_listen,NULL,NULL);
if(sock_conn==-1)
{
perror("accept");
break;
}
if(pthread_create(&tid,NULL,send_file,(void*)sock_conn)!=0)
{
fprintf(stderr,"pthread_create: Create thread fail!\n");
close(sock_conn);
break;
}
}
close(sock_listen);
return 0;
}
//客户端
void* send_file(void* arg)
{
int sock_conn=(int)arg;
send(sock_conn,file_name,sizeof(file_name),0);
char buff[1024];
int ret;
int fd=open(file_path,O_RDONLY);
while(ret=read(fd,buff,sizeof(buff)))
{
//send(sock_conn,buff,ret,0);
write(sock_conn,buff,ret);
}
close(fd);
close(sock_conn);
return NULL;
}
标签:addr,int,文件传输,编程,sock,网络,file,include,conn
From: https://www.cnblogs.com/HappyTeemo/p/18509865