本文介绍了如何在C中编写基于epoll的套接字客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在网上可以找到的所有示例都是服务器.我想使用epoll构建一个基本的Web搜寻器.因此,我需要一个基本的客户示例来入门.
All the examples I can find online are servers. I want to build a basic web crawler using epoll. So I need a basic client example to get me started.
当我说基本"时,我实际上是指一个完整的示例,该示例演示了向实时Web主机发送和接收数据的多种连接.例如,一个简单的HEAD请求及其响应.
When I say basic I really mean a complete example that demonstrates multiple connections with sending and receiving of data to live web hosts. A simple HEAD request and its response for example.
推荐答案
以下是带有epoll的客户端套接字的示例c代码.
Here is a sample c code for client socket with epoll.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 22
#define SERVER "127.0.0.1"
#define MAXBUF 1024
#define MAX_EPOLL_EVENTS 64
int main() {
int sockfd;
struct sockaddr_in dest;
char buffer[MAXBUF];
struct epoll_event events[MAX_EPOLL_EVENTS];
int i, num_ready;
/*---Open socket for streaming---*/
if ( (sockfd = socket(AF_INET, SOCK_STREAM|SOCK_NONBLOCK, 0)) < 0 ) {
perror("Socket");
exit(errno);
}
/*---Add socket to epoll---*/
int epfd = epoll_create(1);
struct epoll_event event;
event.events = EPOLLIN; // Cann append "|EPOLLOUT" for write events as well
event.data.fd = sockfd;
epoll_ctl(epfd, EPOLL_CTL_ADD, sockfd, &event);
/*---Initialize server address/port struct---*/
bzero(&dest, sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_port = htons(PORT);
if ( inet_pton(AF_INET, SERVER, &dest.sin_addr.s_addr) == 0 ) {
perror(SERVER);
exit(errno);
}
/*---Connect to server---*/
if ( connect(sockfd, (struct sockaddr*)&dest, sizeof(dest)) != 0 ) {
if(errno != EINPROGRESS) {
perror("Connect ");
exit(errno);
}
}
/*---Wait for socket connect to complete---*/
num_ready = epoll_wait(epfd, events, MAX_EPOLL_EVENTS, 1000/*timeout*/);
for(i = 0; i < num_ready; i++) {
if(events[i].events & EPOLLIN) {
printf("Socket %d connected\n", events[i].data.fd);
}
}
/*---Wait for data---*/
num_ready = epoll_wait(epfd, events, MAX_EPOLL_EVENTS, 1000/*timeout*/);
for(i = 0; i < num_ready; i++) {
if(events[i].events & EPOLLIN) {
printf("Socket %d got some data\n", events[i].data.fd);
bzero(buffer, MAXBUF);
recv(sockfd, buffer, sizeof(buffer), 0);
printf("Received: %s", buffer);
}
}
close(sockfd);
return 0;
}
这篇关于如何在C中编写基于epoll的套接字客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!