- 论坛徽章:
- 0
|
这是一个服务器端的程序,客户端连上后在客户端打印“Hello World”,然后关掉客户端,
但客户在第一次连接的时候没有相应。以后就正常了。
测试客户端程序 :telnet
测试主机:solaris
各位大侠能否指教一二
#include <stdio.h>;
#include <stdlib.h>;
#include <string.h>;
#include <memory.h>;
#include <ctype.h>;
#include <unistd.h>;
#include <time.h>;
#include <fcntl.h>;
#include <signal.h>;
#include <errno.h>;
#include <stropts.h>;
#include <poll.h>;
#include <sys/types.h>;
#include <sys/stat.h>;
#include <sys/socket.h>;
#include <netinet/in.h>;
#include <netdb.h>;
main(int argc,char **argv)
{
int local_port;
struct sockaddr_in remote,local;
unsigned long rlen;
int sock,client_fd;
int status;
struct pollfd pd;
char buff[2048];
int i=0;
local_port = atoi(argv[1]);
bzero(&local,sizeof(local));
local.sin_addr.s_addr =INADDR_ANY/*inet_addr(local_addr)*/;
local.sin_family = AF_INET;
local.sin_port = htons(local_port);
bzero(&remote,sizeof(remote));
remote.sin_family = AF_INET;
remote.sin_addr.s_addr =INADDR_ANY /*inet_addr(remote_addr)*/;
remote.sin_port = 0;
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
status = bind(sock,(struct sockaddr *)(&local),sizeof(local));
if (status<0)
{
printf("bind %s\n",strerror(errno));
return -1;
}
if (listen(sock,2)==-1)
{
printf("listen %s\n",strerror(errno));
return -1;
}
pd.fd = sock;
pd.events = POLLIN;
pd.revents = 0;
for(;
{
status = poll(&pd,1,-1);
if (status<=0)
{
printf("poll %s\n",strerror(errno));
return -1;
}
if (pd.revents)
{
pd.revents = 0;
rlen = sizeof(remote);
if (client_fd = accept(sock,(struct sockaddr *)&remote,&rlen)==-1)
{
printf("accept %s\n",strerror(errno));
close(client_fd);
continue;
}
printf("received a connection from %s \n",inet_ntoa(remote.sin_addr));
/*
status=recv(client_fd,&buff,sizeof(buff),0);
printf("recv=%d\n",status);
printf("%s\n",buff);
if(status==0)
{
close(client_fd);
continue;
}
memset(buff,sizeof(buff),0);
sprintf(buff,"have send %d pakages",i);
send(client_fd,&buff,sizeof(buff),0);
*/
if (write(client_fd,"Hello,World\n",12)==-1)
perror("write error" ;
i++;
close(client_fd);
}
}
} |
|