c_cpp client_tcp_epoll.c
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp client_tcp_epoll.c相关的知识,希望对你有一定的参考价值。
/*================================================
* Author : Junjie Huang
* Email : acmhjj@gmail.com
* Last modified : 2016-02-15 14:39
* Filename : client_tcp_epoll.c
* Description : TCP客户端,用epoll实现IO多路复用
================================================*/
#include "func.h"
int main (int argc, char const* argv[])
{
if(argc != 3){
printf("args error!\n");
return -1;
}
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == sfd){
perror("socket");
return -1;
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
server_addr.sin_port = htons(atoi(argv[2]));
int ret = connect(sfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
if(-1 == ret){
perror("connect");
close(sfd);
return -1;
}
printf("connect server success!\n");
char buf[128];
int epfd = epoll_create(1);
struct epoll_event epev, epevs[2];
//注册sfd
epev.events = EPOLLIN;
epev.data.fd = sfd;
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, sfd, &epev);
if(-1 == ret){
perror("epoll_ctl1");
close(sfd);
close(epfd);
return -1;
}
//注册STDIN_FILENO
epev.events = EPOLLIN;
epev.data.fd = STDIN_FILENO;
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, STDIN_FILENO, &epev);
if(-1 == ret){
perror("epoll_ctl1");
close(sfd);
close(epfd);
return -1;
}
int i;
while(1){
bzero(epevs, sizeof(epevs));
ret = epoll_wait(epfd, epevs, 2, -1);
if(ret > 0){
for(i = 0; i < ret; i++){
if(epevs[i].data.fd == STDIN_FILENO && epevs[i].events == EPOLLIN){
bzero(buf, sizeof(buf));
read(STDIN_FILENO, buf, sizeof(buf));
ret = send(sfd, buf, strlen(buf) - 1, 0);
if(-1 == ret){
perror("send");
close(sfd);
close(epfd);
return -1;
}
}
if(epevs[i].data.fd == sfd && epevs[i].events == EPOLLIN){
bzero(buf, sizeof(buf));
ret = recv(sfd, buf, sizeof(buf), 0);
if(ret > 0){
printf("%s\n", buf);
}
}
}
}
}
close(sfd);
close(epfd);
return 0;
}
以上是关于c_cpp client_tcp_epoll.c的主要内容,如果未能解决你的问题,请参考以下文章