• libevent实现TCP 客户端


     ibevent实现Tcp Client基于bufferevent实现

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <string.h>
    #include <fcntl.h>
    #include <event2/event.h>
    
    void read_cb(struct bufferevent *bev, void *arg)
    {
        char buf[1024] = {0};
        bufferevent_read(bev, buf, sizeof(buf));
        printf("say:%s
    ", buf);
        bufferevent_write(bev, buf, strlen(buf) +1);
        sleep(1);
    }
    
    void write_cb(struct bufferevent *bev, void *arg)
    {
        printf("我是客户端的写回调函数,没卵用
    ");
    }
    void event_cb(struct bufferevent *bev, short events, void * arg)
    {
        if(events & BEV_EVENT_EOF)
        {
            printf("connection closed 
    );
        }
        else if(events & BEV_EVENT_ERROR)
        {
            printf("some other error
    ");
        }
        else if(events & BEV_EVENT_CONNECTED)
        {
            printf("已经连接了服务器.....
    ");
            return ;
        }
        
        //释放资源
        bufferevent_free(bev);
    }
    //客户端与用户教会,从终端读取数据给服务器
    void read_terminal(evutil_socket_t fd, short what, void *arg)
    {
        //读数据
        char buf[1024] = {0};
        int len = read(fd, buf, sizeof(buf));
        
        struct bufferevent* bev = (struct bufferevent*)arg;
        
        //发送数据
        bufferevent_write(bev, buf, len+1);
    }
    int main()
    {
        struct event_base* base = NULL;
        base = event_base_new();
        
        //通信的fd放到bufferevent中
        struct bufferevent *bev = NULL;
        bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
        
        // init server info
        struct sockaddr_in serv;
        memset(&serv, 0, sizeof(serv));
        serv.sin_family = AF_INET;
        serv.sin_port = htons(9999);
        inet_pton(AF_INET, "127.0.0.1", &serv.sin_addr.s_addr);
        
        //连接服务器
        bufferevent_socket_connect(bev, (struct sockaddr*)&serv, sizeof(serv));
        
        //设置回调
        bufferevent_setcb(bev, read_cb, write_cb, event_cb, NULL);
        
        //设置回调生效
        bufferevent_enable(bev, EV_READ);
        
        //创建事件
        struct event* ev = event_new(base, STDIN_FILENO, EV_READ | EV_PERSIST,
        READ_terminal, bev);
        
        //添加事件
        avent_add(ev, NULL);
        event_base_dispatch(base);
        event_free(ev);
        event_base_free(base);
    }

  • 相关阅读:
    Text Link Ads 注册[赚钱一]
    Linux文件系统中的链接
    C++虚函数和纯虚函数(1)
    Android init reading tips
    Android上GDB的使用
    What is prelink?
    Linux fork哪些被继承,哪些不被继承
    为什么x86 Linux程序起始地址是从0x08048000开始的?
    Android应用开发的插件化 模块化
    C++拷贝构造函数(深拷贝、浅拷贝)
  • 原文地址:https://www.cnblogs.com/woniu201/p/11694507.html
Copyright © 2020-2023  润新知