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\n", buf);
    bufferevent_write(bev, buf, strlen(buf) +1);
    sleep(1);
}

void write_cb(struct bufferevent *bev, void *arg)
{
    printf("我是客戶端的寫回調函數,沒卵用\n");
}
void event_cb(struct bufferevent *bev, short events, void * arg)
{
    if(events & BEV_EVENT_EOF)
    {
        printf("connection closed \n);
    }
    else if(events & BEV_EVENT_ERROR)
    {
        printf("some other error\n");
    }
    else if(events & BEV_EVENT_CONNECTED)
    {
        printf("已經鏈接了服務器.....\n");
        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);
}

相關文章
相關標籤/搜索