- 论坛徽章:
- 0
|
源码修改了一下,如下
#include<arpa/inet.h>
#include<signal.h>
#include<stdio.h>
#include<string.h>
#include<sys/epoll.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
void server(void)
{
int sockSrv=socket(AF_INET,SOCK_STREAM,0);
if(sockSrv==-1)return;
struct sockaddr_in sAddr;
sAddr.sin_family=AF_INET;
sAddr.sin_port =htons(34567);
sAddr.sin_addr.s_addr =htonl(INADDR_ANY);
if(-1 == bind( sockSrv, (struct sockaddr*)&sAddr, sizeof( struct sockaddr )))return;
if(-1 == listen(sockSrv,0))return;
socklen_t cbAddr = sizeof(struct sockaddr);
while(1){
int iAccSock = accept(sockSrv, (struct sockaddr*)&sAddr, &cbAddr );
if(iAccSock==-1)return;
printf("Server: Accepted!\n");
long i=0;
while(1){
char buf[6]={0};
sprintf(buf,"%d",++i);
if(-1 == send(iAccSock,buf,strlen(buf),0) ){
printf("Server: send error\n");
close(iAccSock);
break;
}
printf("Server: data sent=%s\n",buf);
sleep(1);
}
close(iAccSock);
}
}
int createPoll(int hClient)
{
printf("hClient = %d\n", hClient);
int fd_epoll = epoll_create(1);
if(fd_epoll==-1)
{
printf("epoll_create failed\n");
return 0;
}
struct epoll_event ee;
ee.data.fd = hClient;
ee.events=EPOLLIN;
printf("fd_epoll = %d\n", fd_epoll);
int ret=epoll_ctl(fd_epoll,EPOLL_CTL_ADD,hClient,&ee);
if(ret==-1)
{
printf("epoll_ctl failed\n");
return 0;
}
while(1)
{
int fd=epoll_wait(fd_epoll,&ee,1,-1);
if(fd<0)
{
printf("epoll_wait error\n");
continue;
}
if(ee.events&EPOLLIN)
{
printf("Got EPOLLIN\n");
printf("event.data.fd = %d\n", ee.data.fd);
//if(ee.data.fd==hClient)
{
char buf[1024]={0};
if(0>=recv(hClient,buf,sizeof(buf),0)){
printf("Client: recv error\n");
break;
}
printf("Client: recv=%s\n",buf);
}
}
}//end while
}
void client(void)
{
int hClient=socket(AF_INET,SOCK_STREAM,0);
if(hClient==-1)return;
struct sockaddr_in sAddr;
sAddr.sin_family=AF_INET;
sAddr.sin_port =htons(34567);
sAddr.sin_addr.s_addr=inet_addr("127.0.0.1");
if( -1==connect( hClient, (struct sockaddr*)&sAddr, sizeof(struct sockaddr) ) )
{
printf("Client: Async connect error\n");
return;
}
printf("Client: Connected\n");
createPoll(hClient);
close(hClient);
return;
}
int main(void)
{
pid_t pid=fork();
if(pid==0)
{//child
sleep(1);
client();
}
else//father
{
server();
}
return 0;
} |
|