11_6
文件传输:在两台计算机之间进行文件的传递
客户端与服务器连接,客户端与服务器端不在同一个主机之上,要求客户端可以查看服务器端有哪些文件,删除文件,移动文件,归类文件,增添文件夹;下载文件;上传文件,断点续传。
几乎所有的服务器端程序都会有配置文件
自定义文件
(1)socket_info.conf
1 #
2 #
3
4 #ip地址
5 ips=127.0.0.1
6
7 #端口
8 port=6000
9
10 #监听队列大小
11 lismax=5
(2)ser.c
#include "sock_init.h"
#include "work_thread.h"
int main()
{
int sockfd = socket_init();
if ( sockfd == -1 )
{
printf("ser create sockfd failed\n");
exit(0);
}
while( 1 )
{
struct sockaddr_in caddr;
int len = sizeof(caddr);
int c = accept(sockfd,(struct sockaddr*)&caddr,&len);
if ( c < 0 )
{
continue;
}
printf("accept c=%d\n",c);
thread_start(c);
}
}
(3)makefile
all: ser
ser : ser.o sock_init.o work_thread.o
gcc -o ser ser.o sock_init.o work_thread.o -lpthread
ser.o : ser.c
gcc -c ser.c
sock_init.o : sock_init.c
gcc -c sock_init.c
work_thread.o: work_thread.c
gcc -c work_thread.c
clean:
rm -f *.o ser
(4)sock_init.h
#ifndef __SOCK_INIT
#define __SOCK_INIT
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
int socket_init();
#endif
(5)sock_init.c
#include "sock_init.h"
#define IPS "ips="
#define PORT "port="
#define LISMAX "lismax="
struct sock_info
{
char ips[32];
short port;
int lismax;
};
int read_sock_conf(struct sock_info * dt)
{
if ( dt == NULL )
{
return -1;
}
FILE * fp = fopen("socket_info.conf","r");
if ( fp == NULL )
{
printf("open socket_info.conf failed\n");
return -1;
}
int index = 0;
while( 1 )
{
char buff[128] = {0};
char * s = fgets(buff,128,fp);
if ( s == NULL )
{
break;
}
index++;
if ( s[0] == '#' || s[0] == '\n' )
{
continue;
}
s[strlen(s)-1] = '\0';
if ( strncmp(s,IPS,strlen(IPS)) == 0 )
{
strcpy(dt->ips,s+strlen(IPS));
}
else if ( strncmp(s,PORT,strlen(PORT)) == 0 )
{
dt->port = atoi(s+strlen(PORT));
}
else if ( strncmp(s,LISMAX,strlen(LISMAX)) == 0 )
{
dt->lismax=atoi(s+strlen(LISMAX));
}
else
{
printf("不识别的参数:line %d\n",index);
}
}
fclose(fp);
return 0;
}
int socket_init()
{
struct sock_info data;
if ( read_sock_conf(&data) == -1 )
{
return -1;
}
printf("ip=%s\n",data.ips);
printf("port=%d\n",data.port);
printf("lismax=%d\n",data.lismax);
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if ( sockfd == -1 )
{
return -1;
}
struct sockaddr_in saddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(data.port);
saddr.sin_addr.s_addr = inet_addr(data.ips);
int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
if ( res == -1 )
{
return -1;
}
if ( listen(sockfd,data.lismax) == -1 )
{
return -1;
}
return sockfd;
}
(6)work_thread.h
#ifndef __THREAD_START
#define __THREAD_START
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <pthread.h>
void thread_start(int c);
#endif
(7)work_thread.c
#include "work_thread.h"
void* work_thread(void* arg)
{
}
void thread_start(int c)
{
pthread_t id;
pthread_create(&id,NULL,work_thread,(void*)c);
}