使用epoll和多线程实现服务器和客户端的代码

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值