#ifndef _CSERVER_H_
#define _CSERVER_H_
#include "task.h"
#include "message.h"
#include <iostream>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define MAX_BUF_SIZE 200
#define MAX_TMP_SIZE 32
class CServer
{
public:
explicit CServer();
explicit CServer(const char *server_port, const char *server_ip);
bool networkInit();
bool run();
unsigned char *messageHandle(unsigned char *srcbuf,unsigned int srcbuf_len,unsigned int &res_len);
//static void *readThread(void *args);
//static void *writeThread(void *args);
static void *readThread(void *args);
static void *writeThread(void *args);
static void *userdataHandleThread(void *args);
unsigned int getIntfromBuf(unsigned char *srcBuf);
void intWriteToucharBuf(int num,unsigned char *dstBuf);
public:
const static int HEAD_BYTE_NUMS = 4;
private:
void setnonblocking(int sock);
private:
socklen_t m_sinSize;
struct sockaddr_in m_serverAddr;
struct sockaddr_in m_clientAddr;
int m_serverSockfd;
int m_clientSockfd;
int m_epfd;
int m_nfds;
struct epoll_event m_ev;
struct epoll_event m_events[200];
Task *m_readTaskHead;
Task *m_readTaskTail;
Task *m_writeTaskHead;
Task *m_writeTaskTail;
Message *m_rawMsgHead;
Message *m_rawMsgTail;
Message *m_handledMsgHead;
Message *m_handledMsgTail;
pthread_mutex_t m_readMutex;
pthread_cond_t m_readCond;
pthread_mutex_t m_writeMutex;
pthread_cond_t m_writeCond;
pthread_mutex_t m_rawMsgMutex;
pthread_cond_t m_rawMsgCond;
pthread_mutex_t m_handleMsgMutex;
pthread_cond_t m_handleMsgCond;
pthread_t m_readThread;
pthread_t m_writeThread;
pthread_t m_userDataHandleThread;
};
#endif
关于epoll 和 多线程的文章很多,我自身也是在不断的检索一些文章后写下的代码,其中参考其他作者的代码 。
其中主要参考了:http://blog.csdn.net/cuiyifang/article/details/7957937 的代码,在此表示感谢!
代码里添加一些自身的东西,以适应发送不同长度的数据。
这些代码的功能:
1.客户端发送一个加法表达式
2.服务器返回结果。
weixin: 2964215702