问题:
1:accept 最后的参数出错;
2:编程规范严重不足
3:出错异常没有检测,以致问题很难发现
还要注意printf函数说明,这是带缓冲行打印接口,字符串最后最好带回车;
这是我修改过的,请参考,我自己验证通过
//server
int main()
{
//创建套接口
int serfd,clifd;
serfd = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in seraddr,cliaddr;
int addrlen = sizeof(cliaddr);
char buffer[200];
//创建地址
bzero(&seraddr,sizeof(seraddr));
seraddr.sin_family = AF_INET;
seraddr.sin_port = htons(6000);
seraddr.sin_addr.s_addr = htonl(INADDR_ANY);
// 绑定
if(bind(serfd,(struct sockaddr *)&seraddr,sizeof(seraddr))<0)
{
perror("bind");
return -1;
}
//jianting
if(listen(serfd,5)<0)
{
perror("listen");
return -1;
}
printf("ser is listening\n");
//
clifd = accept(serfd,(struct sockaddr*)&cliaddr,(socklen_t*)&addrlen);//最后一参数出错
if(clifd < 0)
{
perror("accept");
return -1;
}
int recvLen = 0;
while(1)
{
memset(buffer,0,sizeof(buffer));
if((recvLen=recv(clifd,buffer,sizeof(buffer),0)) > 0)
{
printf("client send:%s\n",buffer);
}
else if(recvLen == 0)
{
perror("client closed ");
return -1;
}
else
{
perror("recv ");
return -1;
}
}
return 0;
}
//client
int main(int argc,char *argv[])
{
//
int clifd = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in seraddr;
char sendbuf[200];
int sendLen;
seraddr.sin_family = AF_INET;
seraddr.sin_port = htons(6000);
seraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if(connect(clifd,(struct sockaddr *)&seraddr,sizeof(seraddr)) == 0)
printf("linking success!\n");
while(1)
{
scanf("%s",sendbuf);
if(strcmp(sendbuf,"x")==0)
break;
if((sendLen=send(clifd,sendbuf,sizeof(sendbuf),0)) <0 )
{
perror("send error!");
return -1;
}
else if(sendLen == 0)
{
perror("server closed!");
return 0;
}
printf("send data:%s\n",sendbuf);
}
close(clifd);
return 0;
}
我要向楼主学习,我也在看linux 编程,可是停留在信号量这地方,搞的我头昏脑胀,有机会,我要向楼主请教。。。楼主,留下你qq
你把个while循环都去掉就好了 即时聊天不是这么写的