[手游新项目历程]第12天-利用共享内存实现消息队列

Linux进程间通信——使用共享内存  点击打开链接

Linux共享内存编程实例  点击打开链接

利用共享内存实现消息队列  点击打开链接

进程间通信之消息队列   点击打开链接
linux基础编程 共享内存 通过消息队列实现同步 shmget   点击打开链接

用共享内存实现消息队列的设计讨论  点击打开链接

在主线程中慎用WaitForSingleObject (WaitForMultipleObjects)   点击打开链接

CreateMutex,ReleaseMutex,OpenMutex    点击打开链接

WaitForSingleObject 与 EnterCriticalSection 性能比较  点击打开链接

性能调优攻略   点击打开链接

 关于在 Linux 下多个不相干的进程互斥访问同一片共享内存的问题  点击打开链接
深入理解进程间通信之共享内存  点击打开链接
win32下进程间通信(共享内存)实例分析  点击打开链接

浅谈文件内存映射 linux 与 windows 下的不同操作    点击打开链接

共享内存mmap()和CreateFileMapping()  点击打开链接
CreateMutex,ReleaseMutex,OpenMutex  
HANDLE hMutex = CreateMutex(NULL, FALSE, "xiaoyu2");     //创建有名互斥量
WaitForSingleObject(hMutex,INFINITE);
ReleaseMutex(hMutex);

一个简单的消息队列 - 写包
void GateSharememe::WriteBuf(char *szInfo,Tint16  BuffLen)
{
	WaitForSingleObject(hWMutex,INFINITE); 
	t_Time timeNow = Extralib::Timer::DateTime::GetCurMillis();
	//20毫秒发一次包,2000长度发一次包,缓冲10个包发一次包
	if(MAX_SEND_TIME <= timeNow - WriteTime || MAX_SEND_SIZE <= stream.GetPos() || MAX_SEND_COUNT <= count)
	{
		stream.Write(BuffLen);								//消息长度
		stream.WriteBuffer(szInfo,BuffLen);					//消息
		BuffLen = 0;
		stream.Write(BuffLen);								//消息队列结束符号
		memcpy(pBuf, stream.getBuf(), stream.GetBuffSize());
		stream.SetPos(0);
		WriteTime = timeNow;
		count = 0;
	}
	else
	{
		count++;
		stream.Write(BuffLen);					//消息长度
		stream.WriteBuffer(szInfo,BuffLen);		//消息
	}
	ReleaseMutex(hWMutex);
}
收包转发
void SendToClien::SendMsg( char * pBuf)
{
	Stream stream(const_cast<char*>(pBuf),MAX_BUFF_SIZE);
	Tint16 msgLen;
	for (int i = 0;i< MAX_SEND_COUNT;i++)
	{
		stream.Read(msgLen);
		if(msgLen == 0)
			return;
		tagNetMsg sendmsg;
		Stream tmpStream;
		stream.ReadBuffer(tmpStream.getBuf(),msgLen);
		Tint32 ConId; 
		tmpStream.Read(ConId);
		tmpStream.Read(sendmsg);
	
		CLIENT_KEY ClientKey = WebsocketPlayerMgr::Instance()->FindByConnectionId(ConId); 
		if(ClientKey == NULL)
			return;
		LogicalConnection* pClient = FindClient(ClientKey);
		if (pClient)
		{
			WebsocketDataMessage response(EchoCommunication);
			Stream &sendStream = response.getStream() ;	
			sendStream.WriteBuffer((char*)&sendmsg,sendmsg.BuffLen+PACKET_HEAD_SIZE);
			//response.SetArguments(sendStream.getBuf());
			pClient->PushPacket(&response,sendStream.GetPos());
			//ReturnClient(pClient);
		}
		tmpStream.SetPos(0);
		memset(sendmsg.buff,0,sendmsg.BuffLen);
	}
	//测试代码广播
	//BroadcastMsg(pBuf);
}



posted @ 2016-03-09 15:55  byfei  阅读(60)  评论(0编辑  收藏  举报