网络编程基于libevent编写转发服务器,通过magicID进行socket配对,本示例为最初demo可以使用但有bug,仅供参考!!!
#include <netinet/in.h>
#include <sys/socket.h>
#include <fcntl.h>
#include "event2/event.h"
#include "event2/buffer.h"
#include "event2/bufferevent.h"
#include "event2/listener.h"
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define MAX_RELAY_LENGTH 65535
#define MAX_MAGIC_ID 65535
#define MAGIC_LEN 16
#define FLAG 1
typedef struct bev_Buffer_ {
struct bufferevent *bev1;
struct bufferevent *bev2;
} bev_Buffer_t;
bev_Buffer_t *bevBuffer = NULL;
static pthread_mutex_t lock;
static short int MagicId[MAX_MAGIC_ID] = {0};
static short int client_id = 0;
static short int device_id = 0;
//struct bufferevent内建了两个event(read/write)和对应的缓冲区(struct evbuffer *input, *output),并提供相应的函数用来操作> 缓冲区(或者直接操作bufferevent)
//接收到数据后,判断是不一样一条消息的结束,结束标志为"over"字符串
static void readcb(struct bufferevent *bev, void *ctx)
{
#if 1
struct evbuffer *input, *output;
char *request_line;
size_t len;
int count = 0;
input = bufferevent_get_input(bev);//其实就是取出bufferevent中的input
output = bufferevent_get_output(bev);//其实就是取出bufferevent中的output
size_t input_len = evbuffer_get_length(input);
size_t output_len = evbuffer_get_length(output);
/************read msg from bufferevent***********/
char msg[MAX_RELAY_LENGTH+1] = {0};
len = bufferevent_read(bev, msg, sizeof(msg));
/*********get client and device MagicId**********/
if (NULL != strstr(msg,"client")) {
printf("msg =:%s len =:%d\n",msg,len);
if (len > MAGIC_LEN) {
client_id = ntohs(((short int*)msg)[0]);
if( (bevBuffer+client_id)->bev2 == 0) {
(bevBuffer+client_id)->bev2 = bev;
//pthread_mutex_unlock(&lock);//unlock mutex
printf("client_id come:%d\n",client_id);
}
if (device_id == client_id) {
for(count = 0; count < MAX_MAGIC_ID; count++) {
if (MagicId[count] == device_id) {
printf("this magic_id already have\n");
return;
} else if (MagicId[count] == 0) {
MagicId[count] = device_id;
printf("magic_id is:%d\n",MagicId[count]);
return;
}
}
}
} else {
client_id = ntohs(((short int*)msg)[0]);
if( (bevBuffer+client_id)->bev2 == 0) {
(bevBuffer+client_id)->bev2 = bev;
//pthread_mutex_unlock(&lock);//unlock mutex
printf("client_id come:%d\n",client_id);
return;
}
if (device_id == client_id) {
for(count = 0; count < MAX_MAGIC_ID; count++) {
if (MagicId[count] == device_id) {
printf("this magic_id already have\n");
return;
} else if (MagicId[count]