C++聊天室系统源代码 第4页

C++聊天室系统源代码 第4页
数据包类:
class CBuffer
{
public:
 CBuffer(void);
 ~CBuffer(void);
 void SetType(int type);
 void SetHead();  //设置包头,即包大小
 void AddInt(int data);
 void AddData(char* data,int len); //向buf中添加各种数据
 void AddString(string & str);
 void AddCString(CString& str);
 int GetType(); //获取包类型
 int GetPackageSize(); //获取包大小
 int GetInt();
 void GetData(char* buf,int len); //从buf中获取各种数据
 string GetString();
 CString GetCString();
 int Recv(SOCKET s);
 int Send(SOCKET s);
private:
 char* m_buf; //缓存区
 int m_write_index; //写入游标
 int m_readIndex; //读取游标
 int m_used;
};
 

网络通信线程工作函数:

DWORD CServer::WorkThread( LPVOID param )
{
 CServer* pServer = (CServer*)param;
 fd_set read_set;
 while (true)
 {
  FD_ZERO(&read_set);
  FD_SET(pServer->m_server_socket,&read_set);
  for (list<CUser*>::iterator p = pServer->m_users.begin();p != pServer->m_users.end(); ++p)
  {
   FD_SET((*p)->GetSocket(),&read_set);
  }
  if (select(0,&read_set,NULL,NULL,NULL) > 0)
  {
   if(FD_ISSET(pServer->m_server_socket,&read_set))
   {  //有连接加入
    sockaddr_in addrRemote;
    int nAddrLen = sizeof(addrRemote);
    SOCKET client_socket = accept(pServer->m_server_socket,(sockaddr*)&addrRemote,&nAddrLen);
    if (client_socket)
    { //为客户端分配CUser类
     CUser* pUser = new CUser(client_socket);
     pServer->m_users.push_back(pUser);
    }
   }

   for (list<CUser*>::iterator p = pServer->m_users.begin();p != pServer->m_users.end(); ++p)
   {
www.751com.cn
     int ret = (*p)->Recv();
     switch(ret)
     {
     case RECV_ERROR:
      {
       (*p)->Delete(); //发生异常,删除
       break;
      }
     case RECV_FINISH:
      {
       (*p)->AnalyseBuffer(); //完成,分析数据包
       break;
      }
     }
    }
   }
  }
 }

 return 0;
}

接收数据:

int CBuffer::Recv( SOCKET s )
{
 if (m_used < 4)
 { //接受数据包头,即数据包大小
  int len = recv(s,m_buf + m_used,4 - m_used,0);
  if (len == -1)
  {
   return RECV_ERROR;
  }
  m_used += len;
  if (m_used == 4)
  {
   int need  = GetPackageSize();
   if (need <= 0 || need > 512 - 4) //错误的数据包大小
   {
    return RECV_ERROR;
   }
  }
 }
 else
 {
  int need = GetPackageSize(); //接受数据类型和数据
  int len = recv(s,m_buf + m_used,need - m_used + 4,0);
  if (len == -1)
  {
   return RECV_ERROR;

上一页  [1] [2] [3] [4] [5] [6] 下一页

Copyright © 2007-2012 www.chuibin.com 六维论文网 版权所有