该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
贴出代码:
void thd_1(void*);
int main(int argc,char**argv)
{
int s,i,j,k,f;
pthread_t tid;
struct sockaddr_in sa;
fd_set fd;
memset((void*)&sa,0,sizeof(sa));
sa.sin_family=AF_INET;
sa.sin_port=htons(77);
sa.sin_addr.s_addr=htonl(INADDR_ANY);
s=socket(AF_INET,SOCK_STREAM,0);
if(s==-1)
{
printf("error to create socket\n");
return 0;
}
i=bind(s,(struct sockaddr*)&sa,sizeof(sa));
if(i==-1)
{
printf("error to bind\n");
close(s);
return 0;
}
i=listen(s,5);
if(i==-1)
{
printf("error to listen\n");
close(s);
return 0;
}
f=accept(s,NULL,NULL);
if(f==-1)
{
printf("error to accept\n");
close(s);
return 0;
}
i=pthread_create(&tid,NULL,(void*)thd_1,(void*)&f);
if(i!=0)
{
printf("error to crate thread\n");
close(f);
close(s);
return 0;
}
i=pthread_join(tid,NULL);
if(i!=0)
{
printf("error to pthread_join\n");
close(f);
close(s);
return 0;
}
close(f);
close(s);
printf("server will done\n");
return 0;
}
void thd_1(void *v)
{
fd_set fd;
int s,i;
char ch[200];
s=((int*)v)[0];
memset(ch,0,sizeof(ch));
/*while(recv(s,ch,sizeof(ch),0)>0)
{
i=strlen(ch);
send(s,ch,i,0);
memset(ch,0,sizeof(ch));
}*/
while(1)
{
FD_ZERO(&fd);
FD_ISSET(s,&fd);
select(s+1,&fd,NULL,NULL,NULL);
if(FD_ISSET(s,&fd))
{
memset(ch,0,sizeof(ch));
i=recv(s,ch,sizeof(ch),0);
if(i<=0)
{
return;
}
send(s,ch,i,0);
}
}
}
此时,用lsof查看连接,显示客户端可以连上,但是得不到回显。
如果将while(1)的代码注释掉,换用上面while(recv(s,ch,sizeof(ch),0)>0)的代码则可以得到回显�