libevent TCP echo

uppercase.c

cpp 复制代码
/*
 * sudo apt-get install libevent-dev  # libevent-devel for yum
 * Server:
 * cc -g uppercase.c -levent
 * ./a.out
 * Client:
 * $ ncat 192.168.0.107 9995
 * hello, world
 * HELLO, WORLD
 */
#include <stdlib.h> /* free */
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <ctype.h>
#include <signal.h>
#ifndef _WIN32
#include <netinet/in.h>
# ifdef _XOPEN_SOURCE_EXTENDED
#  include <arpa/inet.h>
# endif
#include <sys/socket.h>
#endif

#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <event2/event.h>

#define PORT 9995
#define BUFFER_SIZE 1024

static void listener_cb(struct evconnlistener *, evutil_socket_t,
    struct sockaddr *, int socklen, void *);
static void conn_readcb(struct bufferevent *, void *);
static void conn_eventcb(struct bufferevent *, short, void *);
static void signal_cb(evutil_socket_t, short, void *);

int main(int argc, char **argv) {
    struct event_base *base;
    struct evconnlistener *listener;
    struct event *signal_event;
    struct sockaddr_in sin = {0};

#ifdef _WIN32
    WSADATA wsa_data;
    WSAStartup(0x0201, &wsa_data);
#endif

    base = event_base_new();
    if (!base) {
        fprintf(stderr, "Could not initialize libevent!\n");
        return 1;
    }

    sin.sin_family = AF_INET;
    sin.sin_port = htons(PORT);

    listener = evconnlistener_new_bind(base, listener_cb, (void *)base,
        LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, -1,
        (struct sockaddr*)&sin,
        sizeof(sin));

    if (!listener) {
        fprintf(stderr, "Could not create a listener!\n");
        return 1;
    }

    signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base);

    if (!signal_event || event_add(signal_event, NULL) < 0) {
        fprintf(stderr, "Could not create/add a signal event!\n");
        return 1;
    }

    event_base_dispatch(base);

    evconnlistener_free(listener);
    event_free(signal_event);
    event_base_free(base);

    printf("Server shut down.\n");
    return 0;
}

static void listener_cb(struct evconnlistener *listener, evutil_socket_t fd,
    struct sockaddr *sa, int socklen, void *user_data) {
    struct event_base *base = user_data;
    struct bufferevent *bev;

    bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
    if (!bev) {
        fprintf(stderr, "Error constructing bufferevent!\n");
        event_base_loopbreak(base);
        return;
    }
    bufferevent_setcb(bev, conn_readcb, NULL, conn_eventcb, NULL);
    bufferevent_enable(bev, EV_READ | EV_WRITE);
}

static void conn_readcb(struct bufferevent *bev, void *user_data) {
    struct evbuffer *input = bufferevent_get_input(bev);
    struct evbuffer *output = bufferevent_get_output(bev);
    char *line;
    size_t n, i;

    while ((line = evbuffer_readln(input, &n, EVBUFFER_EOL_LF)) != NULL) {
		if (strncmp(line, "exit", 4)==0 || (strncmp(line, "quit", 4)==0)) {
			free(line);
			bufferevent_free(bev);
			return;
		}
        for (i = 0; i < n; i++) {
            line[i] = toupper((unsigned char)line[i]);
        }
        evbuffer_add(output, line, n);
        evbuffer_add(output, "\n", 1);  /* Add newline for proper response */
        free(line);
    }
}

static void conn_eventcb(struct bufferevent *bev, short events, void *user_data) {
    if (events & BEV_EVENT_EOF) {
        printf("Connection closed.\n");
    } else if (events & BEV_EVENT_ERROR) {
        printf("Got an error on the connection: %s\n", strerror(errno));
    }
    bufferevent_free(bev);
}

static void signal_cb(evutil_socket_t sig, short events, void *user_data) {
    struct event_base *base = user_data;
    struct timeval delay = { 0, 10 };

    printf("Caught an interrupt signal; exiting cleanly in 10ms.\n");
    event_base_loopexit(base, &delay);
}

mzh@raspberrypi:~/workspace $ cc -g uppercase.c -levent

mzh@raspberrypi:~/workspace $ ./a.out

mzh@DESKTOP-GITL67P MINGW64 ~

$ ncat 192.168.0.107 9995

libnsock ssl_init_helper(): OpenSSL legacy provider failed to load.

hello,world

HELLO,WORLD

zjrcu96592

ZJRCU96592

quit

Ncat: ▒▒▒▒▒▒▒▒е▒▒▒▒▒▒ֹ▒▒һ▒▒▒ѽ▒▒▒▒▒▒▒▒ӡ▒ .

相关推荐
Johny_Zhao1 天前
OpenClaw安装部署教程
linux·人工智能·ai·云计算·系统运维·openclaw
blasit1 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
YuMiao2 天前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议
chlk1233 天前
Linux文件权限完全图解:读懂 ls -l 和 chmod 755 背后的秘密
linux·操作系统
舒一笑3 天前
Ubuntu系统安装CodeX出现问题
linux·后端
改一下配置文件3 天前
Ubuntu24.04安装NVIDIA驱动完整指南(含Secure Boot解决方案)
linux
深紫色的三北六号3 天前
Linux 服务器磁盘扩容与目录迁移:rsync + bind mount 实现服务无感迁移(无需修改配置)
linux·扩容·服务迁移
SudosuBash3 天前
[CS:APP 3e] 关于对 第 12 章 读/写者的一点思考和题解 (作业 12.19,12.20,12.21)
linux·并发·操作系统(os)
哈基咪怎么可能是AI4 天前
为什么我就想要「线性历史 + Signed Commits」GitHub 却把我当猴耍 🤬🎙️
linux·github
十日十行4 天前
Linux和window共享文件夹
linux