关于socket()和select()的配合使用

不明白为什么if(select(t+1,&c1,NULL,NULL,(struct timeval *)0)>0)中的时间要用(struct timeval *)0代替,而且不能用其他数字,只能用0。等到以后在慢慢找原因吧,暂时记下来。

以下是从client端传入10个数字,server进行冒泡排序,在传回client.

server端代码

#include <stdlib.h>

#include <stdio.h>

#include <netinet/in.h>

#include <fcntl.h>

#include <string.h>

#define PORT 3333

#define MAX 10

main()

{

int t,r,c,i,j,temp;

int ch[MAX];

fd_set c1;

//struct timeval time;

struct sockaddr_in server,client;

socklen_t len=sizeof(client);

if((t=socket(AF_INET,SOCK_STREAM,0))==-1) {perror("socket");exit(1);}

server.sin_family=AF_INET;

server.sin_port=htons(PORT);

server.sin_addr.s_addr=inet_addr("192.168.0.164");

bzero(&server.sin_zero,sizeof(server.sin_zero));

if(bind(t,(struct sockaddr *)&server,sizeof(struct sockaddr))==-1) {perror("bind");exit(1);}

if(listen(t,20)==-1) {perror("listen");exit(1);}

FD_ZERO(&c1);FD_SET(t,&c1);

while(1)

{

//time.tv_sec=0;

//time.tv_usec=0;

if(select(t+1,&c1,NULL,NULL,(struct timeval *)0)>0)

{

if(FD_ISSET(t,&c1)>0)

{

if((c=accept(t,(struct sockaddr *)&client,&len))==-1) {perror("accept");exit(1);}

if(recv(c,ch,sizeof(int)*MAX,0)==-1) {perror("recv");exit(1);}

for(i=0;i<9;i++)

for(j=i+1;j<10;j++)

if(ch[i]>ch[j]) {temp=ch[i];ch[i]=ch[j];ch[j]=temp;}

if(send(c,ch,sizeof(int)*MAX,0)==-1) {perror("send");exit(1);}

}

else perror("FD_ISSET");

close(c);

}

else perror("select");

}

}

client端代码

#include <stdio.h>

#include <stdlib.h>

#include <netinet/in.h>

#include <string.h>

#define MAX 10

main()

{

struct sockaddr_in client,server;

int a,s,i;

int c[MAX],x[MAX];

printf("请输入要排序的数字\n");

for(i=0;i<MAX;i++)

scanf("%d",&c[i]);

if((s=socket(AF_INET,SOCK_STREAM,0))==-1) {perror("socket");exit(1);}

client.sin_family=AF_INET;

client.sin_port=htons(0);

client.sin_addr.s_addr=INADDR_ANY;

bzero(&(client.sin_zero),sizeof(client.sin_zero));

server.sin_family=AF_INET;

server.sin_port=htons(3333);

inet_aton("192.168.0.164",&(server.sin_addr.s_addr));

bzero(&(server.sin_zero),sizeof(server.sin_zero));

if(bind(s,(struct sockaddr *)&client,sizeof(client))==-1) {perror("bind");exit(1);}

if(connect(s,(struct sockaddr *)&server,sizeof(struct sockaddr))==-1) {perror("connect");exit(1);}

if(send(s,c,sizeof(int)*MAX,0)==-1) {perror("send");exit(1);}

if(recv(s,x,sizeof(int)*MAX,0)==-1) {perror("recv");exit(1);}

printf("原值是:\n");

for(a=0;a<MAX;a++)

printf("%d",c[a]);

printf("\n");

printf("排序完:\n");

for(a=0;a<MAX;a++)

printf("%d",x[a]);

printf("\n");

close(s);

}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzywjd.html