- 论坛徽章:
- 0
|
如果我先启动client端, 每秒循环尝试连接一次server,
然后启动server端, 可是client总也无法连上server.
按照程序逻辑,不应该连接不上啊!
为什么呢,请请大虾支教!!!!
源代码如下:
server:
#include<stdio.h>;
#include<string.h>;
#include<stdlib.h>;
#include<sys/types.h>;
#include<sys/socket.h>;
#include<sys/wait.h>;
#include<netinet/in.h>;
#define myport 8899
void main()
{
char workbuffer[64];
unsigned int opt=1;
int sockfd, newsockfd, ret;
unsigned long size;
struct sockaddr_in sin, theirsin;
sin.sin_family=AF_INET;
sin.sin_port=htons(myport);
sin.sin_addr.s_addr=inet_addr("127.0.0.1" ;
bzero(&(sin.sin_zero), ;
strcpy(workbuffer, "123456789" ;
sockfd=socket(AF_INET, SOCK_STREAM, 0);
setsockopt(sockfd,SOL_SOCKET, SO_REUSEADDR,(char *)&opt, sizeof(int));
while(bind(sockfd,(struct sockaddr *)&sin,sizeof(struct sockaddr))==-1);
printf("binded\n" ;
while(listen(sockfd, 5)==-1);
printf("listened\n" ;
while(1)
{
size=sizeof(struct sockaddr_in);
newsockfd=accept(sockfd, (struct sockaddr *)&theirsin,&size);
if(newsockfd==-1) continue;
printf("accepted\n" ;
if(!fork())
{
send(newsockfd, workbuffer, sizeof(workbuffer), 0);
close(newsockfd);
exit(0);
}
close(newsockfd);
while(waitpid(-1, NULL, WNOHANG)>;0);
}
}
client:
#include<stdio.h>;
#include<string.h>;
#include<stdlib.h>;
#include<sys/types.h>;
#include<sys/socket.h>;
#include<sys/wait.h>;
#include<netinet/in.h>;
#define myport 8899
void main()
{
int sockfd, size;
char workbuffer[64];
struct sockaddr_in theirsin;
unsigned int opt;
memset(workbuffer, 0x00, sizeof(workbuffer));
sockfd=socket(AF_INET, SOCK_STREAM, 0);
opt = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(int));
theirsin.sin_family=AF_INET;
theirsin.sin_port=htons(myport);
theirsin.sin_addr.s_addr=inet_addr("127.0.0.1" ;
bzero(&(theirsin.sin_zero), ;
while(connect(sockfd,(struct sockaddr *)&theirsin,sizeof(struct sockaddr))==-1)
{
printf("wait to connect \n" ;
sleep(1);
continue;
}
size=recv(sockfd, workbuffer, sizeof(workbuffer), 0);
workbuffer[size]=0x00;
close(sockfd);
printf("%s\n", workbuffer);
} |
|