一个非阻塞方式的网络程序模型(UDP)

服务器端:

[ssj@main test]$ cat noneasyserver.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>

#define MAX 80

void my_turn(char *p)
{
if (p == NULL)return;
while( *p != '')
{
if( *p >= (char)0x61 && *p <= (char)0x7a)
*p=(char)((int)*p-(int)0x20);
p++;
}
}

int main(void)
{
struct sockaddr_in sin,cin;
int sfd;
int port=65533;
socklen_t addr_len;
char buf[MAX];
char addr_p[INET_ADDRSTRLEN];
int n,n1,flags;

bzero(&sin,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_addr.s_addr=INADDR_ANY;
sin.sin_port=htons(port);

sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd==-1)
{
perror("Fail to socket");
exit(1);
}

if(bind(sfd,(struct sockaddr *)&sin,sizeof(sin))==-1)
{
perror("Fail to bind");
exit(1);
}

flags=fcntl(sfd,F_GETFL);
flags |= O_NONBLOCK;

if(fcntl(sfd,F_SETFL,flags)==-1)
{
perror("Fail to fcntl");
exit(1);
}

while(1)
{
sleep(5);
bzero(buf,sizeof(buf));
addr_len=sizeof(sin);

n=recvfrom(sfd,buf,MAX,0,(struct sockaddr *)&cin,&addr_len);
if(n==-1&&errno!=EAGAIN)
{
perror("Fail to receiven");
exit(1);
}else if(errno==EAGAIN)
printf("socket are not ready nown");

if(n>=0)
{
inet_ntop(AF_INET,&cin.sin_addr,addr_p,sizeof(addr_p));
printf("Client IP is %s:%dn",addr_p,ntohs(cin.sin_port));
printf("type:%sn",buf);
my_turn(buf);

n1=sendto(sfd,buf,n,0,(struct sockaddr *)&cin,addr_len);
if(n1==-1&&errno!=EAGAIN)
{
perror("Fail to sendto");exit(1);
}else if(errno==EAGAIN)
{
printf("socket ate not ready nown");
}
}

}
if(close(sfd)==-1)
{
perror("Fail to close");exit(1);
}
return 0;
}

客户端:

[ssj@main test]$ cat noneasyclient.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>

#define MAX 80

int main(void)
{
struct sockaddr_in sin,cin;
int port=65533;
socklen_t addr_len;
int sfd;
char buf[MAX];
char add_p[INET_ADDRSTRLEN];
int n;

bzero(&sin,sizeof(sin));
sin.sin_family=AF_INET;
inet_pton(AF_INET,"127.0.0.1",&sin.sin_addr);
sin.sin_port=htons(port);

sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd==-1){perror("Fail to socket");exit(1);}

if(fgets(buf,MAX,stdin)==NULL){perror("Fail to fget");exit(1);}

n=sendto(sfd,buf,strlen(buf)+1,0,(struct sockaddr *)&sin,sizeof(sin));
if(n==-1){perror("Fail to send");exit(1);}

addr_len=sizeof(sin);

n=recvfrom(sfd,buf,MAX,0,(struct sockaddr *)&cin,&addr_len);
if(n==-1)
{
perror("Fail to receiven");
exit(1);
}else
printf("from server:%sn",buf);

if(close(sfd)==-1)
{
perror("Fail to close");exit(1);
}
return 0;

}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注