socket编程实例(文件传输)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
´ËʵÀýÊÇ¿Í»§¶ËÏò·þÎñÆ÷¶Ë´«ËÍÎļþ
·þÎñÆ÷¶Ë´úÂëʵÏÖ£º
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define FU_SERVER_PORT 8080 /*set port*/
#define FU_BUFFERSIZE 1024 /*set buffer size*/
#define FU_LISTENQ 10 /*set listen max conncent*/
int main(int argc,char *argv[])
{
int fu_listenfd,fu_connfd,fu_filefd; /*descriptor*/
int fu_read,fu_write;
int struct_size;
struct sockaddr_in fu_servaddr,fu_cliaddr;
char *fu_filename;
char *p;
char buffer[FU_BUFFERSIZE];
fu_listenfd=socket(AF_INET,SOCK_STREAM,0); /*create socket*/
if(fu_listenfd==-1){
perror("fu_socket");
exit(1);
}
memset(&fu_servaddr,0,sizeof(fu_servaddr)); /*servaddr set 0*/
fu_servaddr.sin_family=AF_INET; /*init serveraddr*/
fu_servaddr.sin_addr.s_addr=INADDR_ANY;
fu_servaddr.sin_port=htons(FU_SERVER_PORT);
/*bind fu_listenfd*/
if(-1==(bind(fu_listenfd,(struct sockaddr *)&fu_servaddr, sizeof(fu_servaddr)))){
exit(1);
}
/*listen fu_listenfd*/
if(-1==(listen(fu_listenfd,FU_LISTENQ))){
perror("fu_listen");
exit(1);
}
/*file upload server start*/
while(1){
printf("file upload server starting......\n");
memset(&fu_cliaddr,0,sizeof(fu_cliaddr));
struct_size=sizeof(fu_cliaddr);
fu_connfd=accept(fu_listenfd,(struct sockaddr *)&fu_cliaddr,&struct_size); if(-1==fu_connfd){
perror("fu_accpet");
continue;
}
fu_filename="/root/backup.txt";
printf("will upload file name is:%s\n",fu_filename);
fu_filefd=open(fu_filename,O_RDWR|O_CREAT|O_TRUNC,S_IRWXU);
if (fu_filefd<0) {
perror("open localhost file");
continue;
}
while(fu_read=read(fu_connfd,buffer,FU_BUFFERSIZE)) {
if (fu_read< 0) {
perror("read client file");
break;
}
if (-1==write(fu_filefd,buffer,fu_read)) {
perror("writing to filefd error");
break;
}
}
if(-1==fu_read||-1==fu_write) continue;
close(fu_filefd);
printf("file upload success!\n");
}
close(fu_listenfd);
return 0;
}
¿Í»§¶Ë´úÂëʵÏÖ£º
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define FU_SERVER_PORT 8080 /*set port*/
#define FU_BUFFERSIZE 1024 /*set buffer size*/
int main(int argc,char *argv[])
{
int fu_sockfd,fu_filefd; /*descriptor*/
int fu_read,fu_write;
int struct_size;
struct sockaddr_in fu_sockaddr;
char *fu_filename;
char *p;
char buffer[FU_BUFFERSIZE];
if (argc!=2) {
perror("fu_Usage: <./client>
exit(1);
}
fu_sockfd=socket(AF_INET,SOCK_STREAM,0); /*create socket*/
if(fu_sockfd==-1){
perror("fu_socket");
exit(1);
}
memset(&fu_sockaddr,0,sizeof(fu_sockaddr)); /*servaddr set 0*/