当前位置:网站首页>Libevent implementation client
Libevent implementation client
2022-04-22 05:02:00 【c1s2d3n4cs】
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#ifdef _WIN32
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "event.lib")
#pragma comment(lib, "event_extra.lib")
#pragma comment(lib, "event_core.lib")
#else
#include <netinet/in.h>
#include <pthread.h>
# ifdef _XOPEN_SOURCE_EXTENDED
# include <arpa/inet.h>
# endif
#include <sys/socket.h>
#define GetCurrentThreadId() pthread_self()
#endif
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <event2/event.h>
#include <event2/thread.h>
static const char MESSAGE[] = "Hello, World!\n";
static const int PORT = 9638;
static struct event_base * createEventBase();
static void conn_writecb(struct bufferevent *, void *);
static void conn_readcb(struct bufferevent *, void *);
static void conn_eventcb(struct bufferevent *, short, void *);
static void timer_callback(evutil_socket_t, short, void *);
static void connect_server(struct event_base* base);
int mainC(int argc, char **argv)
{
struct event_base *base;
struct event* timer = NULL;
#ifdef WIN32
WSADATA wsa_data;
WSAStartup(0x0201, &wsa_data);
#endif
base = createEventBase();
if (!base)
{
fprintf(stderr, "Could not initialize libevent!\n");
return 1;
}
connect_server(base);
// Build and add a timer , Another function of it is to make this iocp The model remains running until... Is called event_base_loopexit
// Found through debugging , When the client is disconnected for some reason , So this iocp The client model will end automatically , because base There are no events in , So I will quit .
// To make this iocp Keep running normally , We can add a permanent timer .
timer = event_new(base, -1, EV_TIMEOUT | EV_PERSIST, timer_callback, NULL);
{
struct timeval timeout = {1,0};
event_add(timer, &timeout);
//event_add(timer, NULL);
}
event_base_dispatch(base); // There's a cycle in here
event_free(timer);
event_base_free(base);
#ifdef WIN32
WSACleanup();
#endif
printf("done\n");
return 0;
}
/**************************************************************************************************************************
libevent Some of the problem records .
1. When reading and writing , There may be a maximum packet byte limit , Because the default is 16384 byte , The following 2 A macro is internally defined .
#define MAX_SINGLE_READ_DEFAULT 16384
#define MAX_SINGLE_WRITE_DEFAULT 16384
Can pass bufferevent_set_max_single_read(...),bufferevent_set_max_single_write(...) To set the maximum value .
*/
static struct event_base * createEventBase()
{
struct event_base *base = NULL;
#if 1
base = event_base_new();
#else
struct event_config *cfg = event_config_new();
#ifdef WIN32
// tell libEvent Use Windows Own thread and synchronization lock , And enable multithreading safety
evthread_use_windows_threads();
//Windows Enable IOCP Pattern
event_config_set_flag(cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
// according to CPU Actual quantity configuration libEvent Of CPU Count
SYSTEM_INFO si;
GetSystemInfo(&si);
event_config_set_num_cpus_hint(cfg, 2);//si.dwNumberOfProcessors
#else
// tell libEvent Use the platform's own threads and synchronization locks , And enable multithreading safety
evthread_use_pthreads();
#endif
base = event_base_new_with_config(cfg);
event_config_free(cfg);
cfg = NULL;
#endif
return base;
}
static void timer_callback(evutil_socket_t fd, short event, void *user_data)
{
struct timeval tv;
evutil_gettimeofday(&tv, nullptr);
printf("it's timeout....%d,%d\n", tv.tv_sec, tv.tv_usec);
}
/*
If you want multiple clients , Just call this... Multiple times , You can also create multiple event_base
*/
static void connect_server(struct event_base* base)
{
//struct sockaddr_in6 sin6; ipv6
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
evutil_inet_pton(sin.sin_family, "127.0.0.1", (void *)&sin.sin_addr);
/* If you want to read, write and release, you can operate safely in other threads , You need to , add to BEV_OPT_THREADSAFE, At the same time, you need to call... At the beginning
evthread_use_windows_threads()、evthread_use_pthreads() Tell the platform to enable multithreading */
struct bufferevent *bev;
#if 1
bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
#else
bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
#endif
if (!bev)
{
return;
}
// Callback function for setting read / write and client connection status
bufferevent_setcb(bev, conn_readcb, conn_writecb, conn_eventcb, 0);
// Set whether the read / write callback is available
bufferevent_enable(bev, EV_WRITE | EV_READ);
if (0 != bufferevent_socket_connect(bev, (struct sockaddr *)&sin, sizeof(sin)))
{
fprintf(stderr, "Could not bufferevent_socket_connect!\n");
}
}
// A callback that occurs after writing data to the client , Usually called bufferevent_write A callback occurred after .
static void conn_writecb(struct bufferevent *bev, void *user_data)
{
struct evbuffer *output = bufferevent_get_output(bev);
if (evbuffer_get_length(output) == 0)
{
printf("flushed answer\n");
}
}
// When receiving the data sent by the client , The function has a callback
static void conn_readcb(struct bufferevent *bev, void *user_data)
{
struct evbuffer *input = bufferevent_get_input(bev);
size_t len = evbuffer_get_length(input);
if (!len)
{
puts(" The number of data received is 0");
return;
}
char data[1025] = "";
size_t size = 0;
// Read the received data from the buffer
while (0 != (size = bufferevent_read(bev, data, 1024)))
{
printf("data=%s, len=%d\n", data, size);
}
const char *wData = "send to client!";
bufferevent_write(bev, wData, strlen(wData) + 1);
// Actively disconnect from the client
//bufferevent_free(bev);
printf("a new conn_readcb %p\n", bev);
}
static void conn_eventcb(struct bufferevent *bev, short events, void *user_data)
{
printf("tcb-bev=%p\n", bev);
if (events & BEV_EVENT_EOF)
{
printf("Connection closed.\n");
}
else if (events & BEV_EVENT_ERROR)
{
printf("Got an error on the connection: %s\n", evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()));
}
else if (events & BEV_EVENT_TIMEOUT)
{
printf("timeout\n");
}
else if (events & BEV_EVENT_CONNECTED)
{
//connected success
printf("connected socket=%d\n", bufferevent_getfd(bev));
return;
}
// None of the other events can happen here, since we haven't enabled timeouts
bufferevent_free(bev);
}
版权声明
本文为[c1s2d3n4cs]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210717211769.html
边栏推荐
- Iris species prediction -- Introduction to data set
- JUnit assertion
- Regular expression validation
- JUnit common notes
- Boyun beyondcmp cloud management platform version 5.6 release
- Application of an open current transformer with switching value
- KNN, cross validation, grid search
- Go parsing command line parameter flag package
- TDD开发模式与DDD开发模式
- 2022.04.20华为笔试
猜你喜欢

One is based on Net core3 1's open source project helps you thoroughly understand the WPF framework prism

Prediction of KNN Iris species after normalization and standardization
![[chestnut sugar GIS] ArcMap - how to combine multiple images into one](/img/b4/fb1ceaf4cbb040ae0fc1d0ffbc46f9.png)
[chestnut sugar GIS] ArcMap - how to combine multiple images into one

Rsync overview

Carina 本地存储入选 CNCF 云原生全景图

Boyun beyondcmp cloud management platform version 5.6 release

6. Comparable to JMeter Net pressure measurement tool - crank practical chapter - collecting diagnosis tracking information and how to analyze bottlenecks
Not sure whether it is a bug or a setting

Autojs automation script how to develop on the computer, detailed reliable tutorial!!!

【Selenium】UnitTest测试框架的基本应用
随机推荐
Overview of over fitting and under fitting treatment methods of linear regression
Junit Introduction et Introduction
How the CPU calls the process
Prometheus basic knowledge brain map
Go parsing command line parameter flag package
Boyun beyondcmp cloud management platform version 5.6 release
[I. XXX pest detection project] 2. Trying to improve the network structure: resnet50, Se, CBAM, feature fusion
Carina's foundation and birth background | deeply understand the first issue of carina series
Linear regression API
Full version operation process Jetson installs the latest opencv
Data segmentation in training set tuning
Summary of 2019 personal collection Framework Library
Summary of topic brushing in April 22
Wos opens the way, and Weimeng makes a new way for SaaS in China
MySQL forget root password solution
Chapter 2 MySQL data types and operators
Chapter IV constraints and indexes
[I. XXX pest detection items] 3. Loss function attempt: focal loss
一个基于.NET Core3.1的开源项目帮你彻底搞懂WPF框架Prism
资源 ACCP-S1 BOOK3开发工具的下载