思维导图
多进程并发服务器通信模型如下
void handler(int signo)
{
while(waitpid()>0);
}
int main()
{
signal(SIGCHLD, handler);
socket();
bind();
listen();
while(1)
{
newfd = accept();
fd = fork();
if(pid > 0)
{
close(newfd);
} else if(pid == 0)
{
close(sfd);
recv();
send();
close(newfd);
exit(EXIT_SUCCESS);
}
}
close(sfd); 关闭监听
}
多线程实现TCP并发服务器的通信模型如下
socket();
bind();
listen();
while(1)
{
newfd = accept();
pthread_create(&tid, NULL, deal_cli_msg, &info);
pthread_detach(tid);
}
void *deal_cli_msg(void *arg)
{
recv();
send();
close();
pthread_exit();
}
作业:编写一个客户端,通过TFTP服务器实现文件的上传和下载
部分代码如下
#include<myhead.h>
#define SER_PORT 69
#define SER_IP "192.168.122.71"
int do_download(int cfd,struct sockaddr_in sin)
{
char buf[516] = "";
short *p1 = (short *)buf;
*p1 = htons(1);
char *p2 = buf+2;
char filename[24]="";
printf("请输入要下载的文件名>>>");
scanf("%s",filename);
getchar();
strcpy(p2, filename);
char *p3 = p2+strlen(p2)+1;
strcpy(p3, "octet");
int len = 4+strlen(p2) + strlen(p3);
sendto(cfd, buf, len, 0, (struct sockaddr*)&sin, sizeof(sin));
printf("下载请求已发送\n");
int fd = -1;
int res=0;
while(1)
{
bzero(buf,sizeof(buf));
if(res=recvfrom(cfd,buf,sizeof(buf),0,NULL,NULL)==-1)
{
perror("recv error");
break;
}
short *opera_id=(short *)buf;
short bid;
if(*opera_id==3)
{
*opera_id=4;
short *pbid=(short*)buf+2;
bid=(short)(*pbid);
char *pdata=(char*)pbid+2;
int datalen = strlen(pdata);
if((*pbid)==1)
{
if(fd=open(filename,O_WRONLY|O_CREAT|O_APPEND,0664)==-1)
{
perror("open error");
return -1;
}
}
if(write(fd,pdata,res-4)==-1)
{
perror("write all");
break;
}
sendto(cfd,buf,4,0,(struct sockaddr*)&sin,sizeof(sin));
if(res <516 )
{
puts("下载完成");
break;
}
}
}
puts("下载完成");
close(fd);
return 0;
}
int do_upload(int cfd,struct sockaddr_in sin)
{
}
int main(int argc, const char *argv[])
{
int cfd = socket(AF_INET, SOCK_DGRAM, 0);
if(cfd == -1)
{
perror("socket error");
return -1;
}
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(SER_PORT);
sin.sin_addr.s_addr = inet_addr(SER_IP);
char menu;
while(1)
{
printf("\t\t====1.download====\n");
printf("\t\t====2.upload====\n");
printf("\t\t====0.exit====\n");
printf("Please enter function options:");
scanf("%c",&menu);
while(getchar() != '\n');
switch(menu)
{
case '1':
{
do_download(cfd,sin);
}
break;
case '2':
{
do_upload(cfd,sin);
}
break;
case '0':
exit(1);
default:
{
printf("enter error!!!");
}
}
printf("Enter any key to clear the screen:");
while(getchar() != '\n');
system("clear");
}
close(cfd);
return 0;
}