Skip to content

Instantly share code, notes, and snippets.

@lotusnowshen
Last active August 29, 2015 14:25
Show Gist options
  • Select an option

  • Save lotusnowshen/58aa2e7e44308af17fd6 to your computer and use it in GitHub Desktop.

Select an option

Save lotusnowshen/58aa2e7e44308af17fd6 to your computer and use it in GitHub Desktop.
client
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#define MAX_LINE 1024
#define ERR_EXIT(m) \
do { \
perror(m);\
exit(EXIT_FAILURE);\
}while(0)
void read_callback(struct bufferevent *bev, void *ctx)
{
char buf[MAX_LINE];
memset(buf, 0, sizeof(buf));
size_t n;
while((n = bufferevent_read(bev, buf, MAX_LINE)) > 0)
{
// bufferevent_write(bev, buf, n);
printf("recv: %s\n", buf);
memset(buf, 0, sizeof(buf));
}
}
void write_callback(struct bufferevent *bev, void *ctx)
{
printf("write\n");
// bufferevent_write(bev, "foobar", strlen("foobar"));
}
struct bufferevent *g_bev = NULL;
void event_callback(struct bufferevent *bev, short event, void *ptr)
{
if (event | BEV_EVENT_CONNECTED)
{
printf("connect ......\n");
bufferevent_write(bev, "hello", strlen("hello"));
// bufferevent_setcb(bev, read_callback, write_callback, event_callback, NULL);
}
else if (event | BEV_EVENT_ERROR)
{
printf("connect error.....\n");
}
}
void *run_in_another_thread(void *arg)
{
struct event_base *base = event_base_new();
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
sin.sin_port = htons(9981);
struct bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
bufferevent_enable(bev, EV_READ|EV_WRITE);
bufferevent_setcb(bev, read_callback, write_callback, event_callback, NULL);
// evbuffer_add(bufferevent_get_output(bev), "hello", strlen("hello"));
g_bev = bev;
if(bufferevent_socket_connect(bev, (struct sockaddr *)&sin, sizeof(sin)) < 0)
{
bufferevent_free(bev);
exit(EXIT_FAILURE);
}
event_base_dispatch(base);
return NULL;
}
int main()
{
pthread_t tid;
pthread_create(&tid, NULL, run_in_another_thread, NULL);
char buf[MAX_LINE];
while (1)
{
if (fgets(buf, MAX_LINE, stdin) == NULL)
break;
bufferevent_write(g_bev, buf, strlen(buf)); // 这里无效
}
pthread_join(tid, NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment