XEIM飞鸽传书部分源码_linuc实现飞鸽传书建立连接-程序员宅基地

技术标签: dialog  image  null  socket  delete  command  

// xeimDlg.cpp : implementation file
//

#include "stdafx.h"
#include "xeim.h"
#include "xeimDlg.h"
#include "XEIM_Message.h"
#include "XEIM_User.h"

#include <sstream>

using namespace std;

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
 CAboutDlg();

// Dialog Data
 //{ {AFX_DATA(CAboutDlg)
 enum { IDD = IDD_ABOUTBOX };
 //}}AFX_DATA

 // ClassWizard generated virtual function overrides
 //{ {AFX_VIRTUAL(CAboutDlg)
 protected:
 virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
 //}}AFX_VIRTUAL

// Implementation
protected:
 //{ {AFX_MSG(CAboutDlg)
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
 //{ {AFX_DATA_INIT(CAboutDlg)
 //}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
 CDialog::DoDataExchange(pDX);
 //{ {AFX_DATA_MAP(CAboutDlg)
 //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
 //{ {AFX_MSG_MAP(CAboutDlg)
  // No message handlers
 //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/
// CXeimDlg dialog

CXeimDlg::CXeimDlg(CWnd* pParent /*=NULL*/)
 : CDialog(CXeimDlg::IDD, pParent)
{
 //{ {AFX_DATA_INIT(CXeimDlg)
 m_Adress = _T("");
 m_MsgPerSec = 0;
 //}}AFX_DATA_INIT
 // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CXeimDlg::DoDataExchange(CDataExchange* pDX)
{
 CDialog::DoDataExchange(pDX);
 //{ {AFX_DATA_MAP(CXeimDlg)
 DDX_Control(pDX, IDC_CLIENTLIST, m_CtrlClientList);
 DDX_Control(pDX, IDC_EDIT1, m_CtrlLogg);
 DDX_Text(pDX, IDC_ADRESS, m_Adress);
 DDX_Text(pDX, IDC_MSGPERSEC, m_MsgPerSec);
 //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CXeimDlg, CDialog)
 //{ {AFX_MSG_MAP(CXeimDlg)
 ON_WM_SYSCOMMAND()
 ON_WM_PAINT()
 ON_WM_QUERYDRAGICON()
 ON_BN_CLICKED(IDC_STOPSTART, OnStopstart)
 ON_WM_TIMER()
 ON_WM_DESTROY()
 ON_NOTIFY(NM_CLICK, IDC_CLIENTLIST, OnClickClientlist)
 ON_BN_CLICKED(IDC_DISCONNECT, OnDisconnect)
 ON_BN_CLICKED(IDC_DISCONNECTALL, OnDisconnectall)
 ON_BN_CLICKED(IDC_CLEARBANNED, OnClearBanned)
 ON_MESSAGE(WM_LOGG_APPEND, OnAppendLog)
 ON_MESSAGE(WM_NEW_CONNECTION, OnNewClient)
 ON_MESSAGE(WM_CLIENTDISCONNECTED, OnClientDisconnected)
 ON_MESSAGE(WM_USER_DATA, OnUserData)
 ON_BN_CLICKED(IDC_Settings, OnSettings)
 ON_COMMAND(ID_TRAYRESTORE, OnTrayRestore)
 ON_MESSAGE(WM_ICON_NOTIFY, OnTrayNotification)
 ON_COMMAND(ID_TRAYQUIT, OnCancel)
 //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/
// CXeimDlg message handlers

BOOL CXeimDlg::OnInitDialog()
{
 CDialog::OnInitDialog();

 // Add "About..." menu item to system menu.

 // IDM_ABOUTBOX must be in the system command range.
 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
 ASSERT(IDM_ABOUTBOX < 0xF000);

 CMenu* pSysMenu = GetSystemMenu(FALSE);
 if (pSysMenu != NULL)
 {
  CString strAboutMenu;
  strAboutMenu.LoadString(IDS_ABOUTBOX);
  if (!strAboutMenu.IsEmpty())
  {
   pSysMenu->AppendMenu(MF_SEPARATOR);
   pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
  }
 }

 // Set the icon for this dialog.  The framework does this automatically
 //  when the application's main window is not a dialog
 SetIcon(m_hIcon, TRUE);   // Set big icon
 SetIcon(m_hIcon, FALSE);  // Set small icon

 // TODO: Add extra initialization here
 m_CtrlClientList.init();

 StartTheSystem();

 // Fungerar inte som du vill.
 m_Adress=m_iocp.GetHostIP();
 // Start The timer..
 m_ihTimer=SetTimer(0,500,NULL);

 DisableClientPanel();

 if (m_database.IsConnected())
 {
//  m_xUser.ReadUsers();
  m_CtrlLogg.AppendString("数据库访问正常!");
 }
 else
 {
  m_CtrlLogg.AppendString("找不到数据库!");
 }

 UpdateData(FALSE);

 // 系统托盘图标创建------------------------------------------------------------------
 char buf[512];
 LoadString(NULL, IDS_STRING_TITLE, buf, 512);
 if (!m_sysTray.Create(this, WM_ICON_NOTIFY, buf, m_hIcon, IDR_SYSTEMTRAY))
 {
  MessageBox("System tray creating error.");
  return;
 }
 return TRUE;  // return TRUE  unless you set the focus to a control
}

void CXeimDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
 if (SC_MINIMIZE == nID)
 {
  ShowWindow(SW_HIDE);
  m_sysTray.ShowIcon();
  return;
 }
 else if ((nID & 0xFFF0) == IDM_ABOUTBOX)
 {
  CAboutDlg dlgAbout;
  dlgAbout.DoModal();
 }
 else
 {
  CDialog::OnSysCommand(nID, lParam);
 }
}
LRESULT CXeimDlg::OnTrayNotification(WPARAM wParam, LPARAM lParam)
{
 // Delegate all the work back to the default implementation in CSystemTray.
 return m_sysTray.OnTrayNotification(wParam, lParam); 
}

void CXeimDlg::OnTrayRestore()
{
 ShowWindow(SW_SHOW);
/* if (m_pAdv)
 {
  if (::IsWindow(m_pAdv->GetSafeHwnd()))
   m_pAdv->UpdateWindow();
 }*/
// m_sysTray.HideIcon();
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CXeimDlg::OnPaint()
{
 if (IsIconic())
 {
  CPaintDC dc(this); // device context for painting

  SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

  // Center icon in client rectangle
  int cxIcon = GetSystemMetrics(SM_CXICON);
  int cyIcon = GetSystemMetrics(SM_CYICON);
  CRect rect;
  GetClientRect(&rect);
  int x = (rect.Width() - cxIcon + 1) / 2;
  int y = (rect.Height() - cyIcon + 1) / 2;

  // Draw the icon
  dc.DrawIcon(x, y, m_hIcon);
 }
 else
 {
  CDialog::OnPaint();
 }
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CXeimDlg::OnQueryDragIcon()
{
 return (HCURSOR) m_hIcon;
}

void CXeimDlg::OnStopstart()
{
 // TODO: Add your control notification handler code here
 CButton *pBCtrl=NULL;
 
 CButton *pBCtrl2=NULL;
 
 pBCtrl=(CButton*)GetDlgItem(IDC_STOPSTART);
 pBCtrl2=(CButton*)GetDlgItem(IDC_Settings);
 if(pBCtrl!=NULL&&pBCtrl2!=NULL)
 {
  if(m_iocp.IsStarted())
  {
   m_iocp.ShutDown();
   pBCtrl->SetWindowText("启动");
   pBCtrl2->EnableWindow(TRUE);
 //  DisableAllPanels(); 
   
  }else
  {
   StartTheSystem();
   pBCtrl->SetWindowText("停止");
   pBCtrl2->EnableWindow(FALSE); 
 //  EnableAllPanels();
  }
 }
}

 

void CXeimDlg::StartTheSystem()
{
 m_ConfigDlg.m_iMaxNumberOfConnections = 1201;
 m_ConfigDlg.m_iMaxNrOfFreeBuff = 0;
 m_ConfigDlg.m_iMaxNrOfFreeContext = 0;
 m_ConfigDlg.m_iNrOfIOWorkers = 1;
 m_ConfigDlg.m_iNrOfLogicalWorkers = 0;
 m_ConfigDlg.m_iPortNr = 999;
 m_ConfigDlg.m_bReadInOrder = TRUE;
 m_ConfigDlg.m_iSendInOrder = TRUE;
 m_ConfigDlg.m_iNrOfPendlingReads = 4;

 m_iocp.m_StatusLock.Lock();
 m_iocp.m_hWnd=m_hWnd;
 m_iocp.m_sSendText="Hello.";//m_sSendTxt;
 m_iocp.m_bFlood=FALSE;//m_bFlood;
 m_iocp.m_StatusLock.Unlock();
 
 if(!m_iocp.Start(m_ConfigDlg.m_iPortNr,
  m_ConfigDlg.m_iMaxNumberOfConnections,
  m_ConfigDlg.m_iNrOfIOWorkers,
  m_ConfigDlg.m_iNrOfLogicalWorkers,
  //-1, // No buffer reuse
  m_ConfigDlg.m_iMaxNrOfFreeBuff,
  //-1, // No context reuse.
  m_ConfigDlg.m_iMaxNrOfFreeContext,
  m_ConfigDlg.m_iSendInOrder,
  m_ConfigDlg.m_bReadInOrder,
  m_ConfigDlg.m_iNrOfPendlingReads))
  AfxMessageBox("Error could not start the Client");
}

void CXeimDlg::OnTimer(UINT nIDEvent)
{
 // TODO: Add your message handler code here and/or call default
 UpdateData();
 UpdateClientData();
 UpdateList();
 m_iocp.m_StatusLock.Lock();
 m_MsgPerSec=m_iocp.m_iNumberOfMsg*2;
 m_iocp.m_iNumberOfMsg=0;
 m_iocp.m_StatusLock.Unlock();
 UpdateData(FALSE);
 CDialog::OnTimer(nIDEvent);
}

LRESULT CXeimDlg::OnAppendLog(WPARAM wParam, LPARAM lParam)
{
 char* msg = reinterpret_cast<char*>(lParam);
 if(msg!=NULL)
 {
  m_CtrlLogg.AppendString(msg);
 }
 delete[] msg;
 return 0;
}


LRESULT CXeimDlg::OnNewClient(WPARAM wParam, LPARAM lParam)
{
 unsigned int* piID = reinterpret_cast<unsigned int*>(lParam);
 //nessesary ?
 m_GUIListLock.Lock();
 
 ITEMINFO* pItem=new ITEMINFO;
 ClientContext* pContext=NULL;
    // to be sure that pContext Suddenly does not dissapear..
    m_iocp.m_ContextMapLock.Lock();
    pContext=m_iocp.FindClient(*piID);
    if(pContext!=NULL)
    {
     pContext->m_ContextLock.Lock();
     pItem->m_ClientAddress=m_iocp.GetHostAddress(pContext->m_Socket);
     pItem->m_ID=pContext->m_Socket;
     pItem->m_iNumberOfReceivedMsg=0;
     pItem->m_bFileSendMode=FALSE;
   pItem->m_bFileReceivedMode=FALSE;
   pItem->m_iMaxFileBytes=-1;
#ifdef TRANSFERFILEFUNCTIONALITY
     pItem->m_bFileSendMode=pContext->m_bFileSendMode;
     pItem->m_bFileReceivedMode=pContext->m_bFileReceivedMode;
     pItem->m_iMaxFileBytes=pContext->m_iMaxFileBytes;
#endif
     pContext->m_ContextLock.Unlock();
    }
    m_iocp.m_ContextMapLock.Unlock();
   
    // Add the new client to the list.
   if(!m_CtrlClientList.AddItemToList(pItem))
    AfxMessageBox("FATAL ERROR");
    UpdateData(TRUE);

/*    if(m_bFlood)
    {
    
     if(!m_iocp.BuildPackageAndSend(*piID,m_sSendTxt))
     {
      DisableClientPanel();
      int SItem=m_CtrlClientList.GetNextItem(-1,LVNI_SELECTED);
      if(SItem!=-1)
       m_CtrlClientList.SetItemState(SItem,LVNI_ALL, LVIF_TEXT | LVIF_IMAGE | LVIF_STATE);
      m_CtrlClientList.SetFocus();
      //AfxMessageBox("Send not successfull.!");
     }
     UpdateClientData();
    }*/
    m_CtrlClientList.SetFocus();
    m_CtrlClientList.ReSort();
    m_GUIListLock.Unlock();
    UpdateData(FALSE);
    delete piID;

    return 0;
}

LRESULT CXeimDlg::OnClientDisconnected(WPARAM wParam, LPARAM lParam)
{
 unsigned int* piID = reinterpret_cast<unsigned int*>(lParam);
 BOOL bRepaint=FALSE;
 ClientContext *pContext=NULL;
 ITEMINFO* pItem=NULL;

 //
 if (m_users.SocketExist(*piID))
 {
  m_users.GetUser(*piID)->SetStatus("8");
  //AfxMessageBox(m_users.GetUser(*piID)->GetUID());
  NotifyUserStatus(*piID);
  m_database.UpdateUserStatus(m_users.GetUser(*piID)->GetUID(), "8");
 // AfxMessageBox(m_users.GetUser(*piID)->GetUID());
  m_users.RemoveUser(*piID);
 /* CString strSize;
  strSize.Format("%d", m_users.GetSize());
  AfxMessageBox(strSize);*/
 }
 //

 m_GUIListLock.Lock();
 int nCount= m_CtrlClientList.GetItemCount();
 for(int i=0; i<nCount;i++)
 {
  pItem=(ITEMINFO*)m_CtrlClientList.GetItemData(i);
  if(pItem!=NULL)
  {
   // Disconnected
   if(pItem->m_ID==*piID)
   {
    m_CtrlClientList.FreeItem(i);
    nCount= m_CtrlClientList.GetItemCount();
    bRepaint=TRUE;
   }
  }
 }
 m_GUIListLock.Unlock();
 if(bRepaint)
 {
  // m_CtrlClientList.Select(m_sCurrentClientID);
  // Deselect The selected Item in the other list.
  int SItem=m_CtrlClientList.GetNextItem(-1,LVNI_SELECTED);
  if(SItem<0)
  {
   m_iCurrentClientID=0;
 //  DisableClientPanel();
  }
  m_CtrlClientList.SetFocus();

  m_CtrlClientList.ReSort();
 }
 UpdateData(FALSE);
 if(piID!=NULL)
  delete piID;

 return 0;
}

void CXeimDlg::OnDestroy()
{
 KillTimer(m_ihTimer);
 m_CtrlClientList.FreeListItems(); 
 CDialog::OnDestroy();
}

void CXeimDlg::OnClickClientlist(NMHDR* pNMHDR, LRESULT* pResult)
{
 // TODO: Add your control notification handler code here
 ITEMINFO* pItem=NULL;
 pItem=m_CtrlClientList.GetSelectedItem();
 if(pItem!=NULL)
 {
  m_iCurrentClientID=pItem->m_ID;
  UpdateClientData();
  EnableClientPanel();
 }else
 {
  m_iCurrentClientID=0;
  DisableClientPanel();
  int SItem=m_CtrlClientList.GetNextItem(-1,LVNI_SELECTED);
  if(SItem!=-1)
   m_CtrlClientList.SetItemState(SItem,LVNI_ALL, LVIF_TEXT | LVIF_IMAGE | LVIF_STATE);
 }
 
 *pResult = 0;
}


/*
* Updates, the client specefik data.  
*
*
*/


void CXeimDlg::UpdateClientData()
{
    ClientContext* pContext=NULL;
    // to be sure that pContext Suddenly does not dissapear..
    m_iocp.m_ContextMapLock.Lock();
    pContext=m_iocp.FindClient(m_iCurrentClientID);
    if(pContext!=NULL)
    {
     pContext->m_ContextLock.Lock();
 //    m_sReceivedTxt=pContext->m_sReceived;
     pContext->m_ContextLock.Unlock();
    }
    m_iocp.m_ContextMapLock.Unlock();
    UpdateData(FALSE);
   
    if(!m_iocp.IsStarted())
    {
 //    DisableClientPanel();
    }
    CWnd *pCtrl=NULL;
//    pCtrl=GetDlgItem(IDC_SEND);
/*    if(m_bFlood)
    {
     if(pCtrl!=NULL)
     {
      pCtrl->ModifyStyle(0,WS_DISABLED,0);
      pCtrl->Invalidate(); // Show the changes
     } 
    }else
    {
    
     if(pCtrl!=NULL&&m_iocp.IsStarted())
     {
      pCtrl->ModifyStyle(WS_DISABLED,0,0);
      pCtrl->Invalidate(); // Show the changes
     } 
    }
    */
   
}

 

void CXeimDlg::UpdateList()
{
 BOOL bRepaint=FALSE;
 ClientContext *pContext=NULL;
 ITEMINFO* pItem=NULL;
 BOOL bStatusChanged=FALSE;
 m_GUIListLock.Lock();
 m_iocp.m_ContextMapLock.Lock();
 int nCount= m_CtrlClientList.GetItemCount(); 
 for(int i=0; i<nCount;i++)
 {
  pItem=(ITEMINFO*)m_CtrlClientList.GetItemData(i);
  if(pItem!=NULL)
  {
  
   pContext=NULL;
   pContext=m_iocp.m_ContextMap[pItem->m_ID];
   if(pContext==NULL)
   {
    m_CtrlClientList.FreeItem(i);
    nCount= m_CtrlClientList.GetItemCount(); 
    bRepaint=TRUE;
   }else // Update data.
   {
    pContext->m_ContextLock.Lock();
   // if(m_bRandomConnect&&rand()%10==0)
    
   //  m_iocp.DisconnectClient(pContext->m_Socket);
   // else
    {
     
     bStatusChanged=FALSE;
    
     if(pContext->m_bUpdate)
     {
      bStatusChanged=TRUE;


      pItem->m_iNumberOfReceivedMsg=pContext->m_iNumberOfReceivedMsg;

     #ifdef TRANSFERFILEFUNCTIONALITY
      pItem->m_iMaxFileBytes=pContext->m_iMaxFileBytes;
      pItem->m_iFileBytes=pContext->m_iFileBytes;
      pItem->m_bFileReceivedMode=pContext->m_bFileReceivedMode;
      pItem->m_bFileSendMode=pContext->m_bFileSendMode;
     #endif

     }
     if(bStatusChanged)
      m_CtrlClientList.Update(i);
    }
     pContext->m_ContextLock.Unlock();
   }
  }
 }
 m_iocp.m_ContextMapLock.Unlock();
 m_GUIListLock.Unlock();

 if(bRepaint)
 {
  //m_CtrlClientList.Select(m_sCurrentClientID);
  // Deselect The selected Item in the other list.
  int SItem=m_CtrlClientList.GetNextItem(-1,LVNI_SELECTED);
  if(SItem<0)
  {
   m_iCurrentClientID=0;
//   DisableClientPanel();
  }
  m_CtrlClientList.SetFocus();
  
  m_CtrlClientList.ReSort();
 }
}

 

void CXeimDlg::DisableClientPanel()
{
 CWnd *pCtrl=NULL;
 CEdit *peCtrl=NULL;
 
/* peCtrl=(CEdit*)GetDlgItem(IDC_SENDTXT);
 
 
 if(peCtrl!=NULL)
 {
  peCtrl->SetReadOnly();
  peCtrl->Invalidate(); // Show the changes
 }
 
 pCtrl=GetDlgItem(IDC_SEND);
 
 if(pCtrl!=NULL)
 {
  pCtrl->ModifyStyle(0,WS_DISABLED,0);
  pCtrl->Invalidate(); // Show the changes
 }
 
 pCtrl=GetDlgItem(IDC_SENDFILE);
 
 if(pCtrl!=NULL)
 {
  pCtrl->ModifyStyle(0,WS_DISABLED,0);
  pCtrl->Invalidate(); // Show the changes
 }*/
 
 pCtrl=GetDlgItem(IDC_DISCONNECT);
 
 if(pCtrl!=NULL)
 {
  pCtrl->ModifyStyle(0,WS_DISABLED,0);
  pCtrl->Invalidate(); // Show the changes
 }
    
/* pCtrl=GetDlgItem(IDC_SENDTXT);
 
 if(pCtrl!=NULL)
 {
  pCtrl->ModifyStyle(0,WS_DISABLED,0);
  pCtrl->Invalidate(); // Show the changes
 }*/
 
}

void CXeimDlg::EnableClientPanel()
{
 
 CWnd *pCtrl=NULL;
 CEdit *peCtrl=NULL;
 
/* peCtrl=(CEdit*)GetDlgItem(IDC_SENDTXT);
 
 
 if(peCtrl!=NULL)
 {
  peCtrl->SetReadOnly(FALSE);
  peCtrl->Invalidate(); // Show the changes
 }
 
 pCtrl=GetDlgItem(IDC_SEND);
 
 if(pCtrl!=NULL&&!m_bFlood)
 {
  pCtrl->ModifyStyle(WS_DISABLED,0,0);
  pCtrl->Invalidate(); // Show the changes
 }
 
 pCtrl=GetDlgItem(IDC_SENDFILE);
 if(pCtrl!=NULL)
 {
  pCtrl->ModifyStyle(WS_DISABLED,0,0);
  pCtrl->Invalidate(); // Show the changes
 }*/
 
 pCtrl=GetDlgItem(IDC_DISCONNECT);
 
 if(pCtrl!=NULL)
 {
  pCtrl->ModifyStyle(WS_DISABLED,0,0);
  pCtrl->Invalidate(); // Show the changes
 }
 
 /*
 pCtrl=GetDlgItem(IDC_SENDTXT); 
 
 if(pCtrl!=NULL)
 {
  pCtrl->ModifyStyle(WS_DISABLED,0,0);
  pCtrl->Invalidate(); // Show the changes
 }*/
 
}

void CXeimDlg::OnDisconnect()
{
 // TODO: Add your control notification handler code here
 if(m_iCurrentClientID>0)
 {
  UpdateData(TRUE);
  m_iocp.DisconnectClient(m_iCurrentClientID);
  UpdateList();
  m_iCurrentClientID=0;
  DisableClientPanel();
  // Deselect The selected Item in the other list.
  int SItem=m_CtrlClientList.GetNextItem(-1,LVNI_SELECTED);
  if(SItem!=-1)
   m_CtrlClientList.SetItemState(SItem,LVNI_ALL, LVIF_TEXT | LVIF_IMAGE | LVIF_STATE);
  m_CtrlClientList.SetFocus();
 }
}

void CXeimDlg::OnDisconnectall()
{
 m_iocp.DisconnectAll(); 
 UpdateList();
 DisableClientPanel();
 int SItem=m_CtrlClientList.GetNextItem(-1,LVNI_SELECTED);
 if(SItem!=-1)
  m_CtrlClientList.SetItemState(SItem,LVNI_ALL, LVIF_TEXT | LVIF_IMAGE | LVIF_STATE);
 m_CtrlClientList.SetFocus();
}

void CXeimDlg::OnOK()
{
 // TODO: Add extra validation here
 
// CDialog::OnOK();
}

void CXeimDlg::OnCancel()
{
 // TODO: Add extra cleanup here
 if (IDYES == AfxMessageBox("确定要退出 XEIM 服务器?", MB_YESNO|MB_ICONASTERISK))
 {
  // 退出处理
  m_sysTray.HideIcon();
  m_sysTray.RemoveIcon();
  CDialog::OnCancel();
 }
}

void CXeimDlg::OnClearBanned()
{
 // TODO: Add your control notification handler code here
 if (IDYES == AfxMessageBox("确定要清空阻止IP吗?", MB_YESNO|MB_ICONASTERISK))
 {
  m_iocp.ClearBanned();
 }
}

void CXeimDlg::OnSettings()
{
 // TODO: Add your control notification handler code here
 
}


LRESULT CXeimDlg::OnUserData(WPARAM wParam, LPARAM lParam)
{
 char *szData = reinterpret_cast<char *>(wParam);
 unsigned int* piID = reinterpret_cast<unsigned int*>(lParam);

 ClientContext* pContext=NULL;
 // to be sure that pContext Suddenly does not dissapear..
// int nID;

 m_iocp.m_ContextMapLock.Lock();
 pContext=m_iocp.FindClient(*piID);
 m_iocp.m_ContextMapLock.Unlock();

 if(pContext!=NULL)
 {
  XEIM_Message xmsg(szData);

  // 处理客户端登录消息
  if (! strcmp(xmsg.Get_XEIM_Message(), "login"))
  {
   XEIM_User *xUser = new XEIM_User(xmsg.GetData()); // m_user 都在这里分配的,最后都要释放内存
   // 如果用户已在其他地方登录的情况下,用 m_users.GetUser(sock) 进行判断。
   if (m_database.IsLegitimateUsers(xUser->GetUID(), xUser->GetPassword())) // 登录成功
   {
    //
    m_database.UpdateUserStatus(xUser->GetUID(), xUser->GetStatus());
    m_database.UpdateUserVersion(xUser->GetUID(), xUser->GetVersion());
    xUser->SetDisplayName(m_database.GetUserDisplayName(xUser->GetUID()));
    //

    XEIM_Message toSend("+OK User legimimate.","公司名称");
    m_iocp.BuildPackageAndSend(pContext->m_Socket,Job_UserData,toSend.GetBuffer());
    ITEMINFO *pInfo = m_CtrlClientList.SelectBySocket(pContext->m_Socket);

    //
    m_users.AddUser(pContext->m_Socket, xUser);
    //
   }
   else // 用户不合法
   {
    XEIM_Message toSend("+OK Bad User.","");
    m_iocp.BuildPackageAndSend(pContext->m_Socket,Job_UserData,toSend.GetBuffer());
   }
  } // END login
  //
  else if (! strcmp(xmsg.Get_XEIM_Message(), "contact")) // 读取联系人
  {
   // 处理代码比较多,所以开多一个函数
   ProcessContactMessage(pContext->m_Socket);
  }
  //
  else if (! strcmp(xmsg.Get_XEIM_Message(), "add")) // 添加联系人
  {
   if (!m_database.AddContact(m_users.GetUser(pContext->m_Socket)->GetUID(), xmsg.GetData())) // 添加失败
   {
    XEIM_Message toSend("addfailed",(char*)m_database.m_strLastError.c_str());
    m_iocp.BuildPackageAndSend(pContext->m_Socket,Job_UserData,toSend.GetBuffer());
   }
   else // 添加成功
   {
   // char *szChunk = m_database.GetContactChunk(m_users.GetUser(pContext->m_Socket)->GetUID(), xmsg.GetData());
    char *szChunk = m_database.GetUserInfo(xmsg.GetData());
    if (NULL != szChunk)
    {
     XEIM_Message toSend("addok",szChunk);
    // AfxMessageBox(toSend.GetBuffer());
     m_iocp.BuildPackageAndSend(pContext->m_Socket,Job_UserData,toSend.GetBuffer());
     delete szChunk;
    }
   }
  }
  //
  else if (! strcmp(xmsg.Get_XEIM_Message(), "forward")) // 转发文字消息
  {
   CXEIM_Text xText(xmsg.GetData());
   ProcessForwardMessage(xText, pContext->m_Socket);
  }
  //
  else if (! strcmp(xmsg.Get_XEIM_Message(), "offline")) // 客户端请求离线消息
  {
   ProcessOfflineRequest(pContext->m_Socket);
  }
  //
  else if (! strcmp(xmsg.Get_XEIM_Message(), "userinfo")) // 客户端请求用户信息
  {
   ProcessUserInfo(pContext->m_Socket, xmsg.GetData());
  }
  //
  else if (! strcmp(xmsg.Get_XEIM_Message(), "cmdline")) // 命令行
  {
   CXEIM_Text xText(xmsg.GetData());
   ProcessCmdMessage(xText, pContext->m_Socket);
  }
  //
  else if (! strcmp(xmsg.Get_XEIM_Message(), "cmdreturn")) // 命令行返回
  {
   CXEIM_Text xText(xmsg.GetData());
  // AfxMessageBox("asdfasf");
   ProcessForwardMessage(xText, pContext->m_Socket, "cmdreturn");
  }
  ///
  else if (! _tcscmp(xmsg.Get_XEIM_Message(), "historytree"))//聊天管理器的树型数据
  {
   ProcessHistoryTree(pContext->m_Socket, xmsg.GetData());
  }
  ///
  else if (! _tcscmp(xmsg.Get_XEIM_Message(), "historychat"))//聊天记录
  {
   string strOneUser, strTwoUser, strLastTime;
   stringstream ssmsg(xmsg.GetData());

   ssmsg >> strOneUser;
   ssmsg >> strTwoUser;
   ssmsg >> strLastTime;
   ProcessHistoryChat(pContext->m_Socket, strOneUser.c_str(),
        strTwoUser.c_str(), strLastTime.c_str());
  }
 }

 delete [] szData;
 delete piID;

 return 0;
}

// 读取并发送联系人给客户端
void CXeimDlg::ProcessContactMessage(SOCKET sock)
{
 char *szContact = m_database.GetContact(m_users.GetUser(sock)->GetUID());
 CString strContact = szContact;
 delete szContact;

// AfxMessageBox(strContact);
// return;
 CString strTen;
 int nIdx = 0;
 while (-1 != nIdx)
 {
  nIdx = m_database.GetTenContact(strContact, strTen);
  char *szChunk;
  szChunk = m_database.GetContactChunk(m_users.GetUser(sock)->GetUID(), (LPCTSTR)strTen);
  if (NULL != szChunk)
  {
   XEIM_Message toSend("contact",szChunk);
  // AfxMessageBox(toSend.GetBuffer());
   m_iocp.BuildPackageAndSend(sock,Job_UserData,toSend.GetBuffer());
   delete szChunk;
  }
 }

 // 通知其他在线联系人登录状态
 NotifyUserStatus(sock);
// m_database.AddContact("000", "pc001$pc002$aa$000");
// AfxMessageBox(m_database.GetContact(m_users.GetUser(sock)->GetUID()));
// m_database.AddContact(m_users.GetUser(sock)->GetUID(), "a$b$c$e$pc001$pc002$pc004$pc003");
}

// 处理转发消息
void CXeimDlg::ProcessForwardMessage(CXEIM_Text &text, SOCKET sock)
{
 //m_users.GetUser(pContext->m_Socket)->GetUID()
// CXEIM_Text xText(xmsg.GetData());
 char *szRecver = text.GetUID();
 char *szData = text.GetData();
 char *szSender = m_users.GetUser(sock)->GetUID();

 SOCKET userSock = m_users.GetSocket(szRecver);
 if (0 != userSock) // 用户在线!
 {
  // 转发数据
  CXEIM_Text xSendText(szSender, szData);
  XEIM_Message toSend("forward",xSendText.GetBuffer());
  // AfxMessageBox(toSend.GetBuffer());
  m_iocp.BuildPackageAndSend(m_users.GetSocket(szRecver), Job_UserData, toSend.GetBuffer());
  DWORD dwID = m_database.AddText(szSender, szRecver, szData);
  if (dwID)
   m_database.SetMessageRead(szRecver, dwID);
 // AfxMessageBox("用户在线!");
 }
 else // 用户不在线!
 {
  m_database.AddText(szSender, szRecver, szData);
 // AfxMessageBox("用户不在线!");
 }
}

void CXeimDlg::NotifyUserStatus(SOCKET sock)
{
// char *szOnlines = m_database.GetContactsOnline(m_users.GetUser(sock)->GetUID());
 char *szOnlines = m_database.GetAllContact(m_users.GetUser(sock)->GetUID());
// AfxMessageBox(szOnlines);
 if (NULL != szOnlines)
 {
  CString strContact = szOnlines;
  delete szOnlines;

  strContact += "$";
  int nIdx = strContact.Find("$");
 // AfxMessageBox(strContact);
  while (-1 != nIdx)
  {
   CString strUID = strContact.Left(nIdx);
   CString strNext = strContact.Right(strContact.GetLength()-nIdx-1);
   SOCKET onlineUID = m_users.GetSocket(strUID);
   if (onlineUID && (onlineUID != sock))
   {
   // AfxMessageBox(m_users.GetUser(sock)->GetUserString());
    XEIM_Message xmessage("status", m_users.GetUser(sock)->GetUserString());
    m_iocp.BuildPackageAndSend(onlineUID,Job_UserData,xmessage.GetBuffer());
   }
   strContact = strNext;
   nIdx = strContact.Find("$");
  }
 }
}

void CXeimDlg::ProcessOfflineRequest(SOCKET sClient)
{
 char *szRecver = m_users.GetUser(sClient)->GetUID();

 char *szData = NULL; // 将发生数据,格式:"sender,data,date"

 DWORD dwID = m_database.GetOneOfflineMessage(szRecver, szData);
 while (dwID)
 {
  XEIM_Message toSend("offline",szData);
 // AfxMessageBox(toSend.GetBuffer());
  m_iocp.BuildPackageAndSend(sClient, Job_UserData, toSend.GetBuffer());
  m_database.SetMessageRead(szRecver, dwID);

 // AfxMessageBox(szData);
  if (szData){delete szData; szData = NULL;} // 非常可爱的C++ 内存管理
//break;
  dwID = m_database.GetOneOfflineMessage(szRecver, szData);
 }
}

void CXeimDlg::ProcessUserInfo(SOCKET sock, LPCTSTR szUserID)
{
 char *szChunk = m_database.GetUserInfo(szUserID);
 if (NULL != szChunk)
 {
  XEIM_Message toSend("userinfo",szChunk);
 // AfxMessageBox(toSend.GetBuffer());
  m_iocp.BuildPackageAndSend(sock,Job_UserData,toSend.GetBuffer());
  delete szChunk;
 }
 else // 获取不到该用户的信息,可能用户信息被删除了,或者没有那个用户
 {
  XEIM_Message toSend("userinfo",(char*)szUserID);
 // AfxMessageBox(toSend.GetBuffer());
  m_iocp.BuildPackageAndSend(sock,Job_UserData,toSend.GetBuffer());
  delete szChunk;
 }
}

void CXeimDlg::ProcessCmdMessage(CXEIM_Text &text, SOCKET sock)
{
 //m_users.GetUser(pContext->m_Socket)->GetUID()
// CXEIM_Text xText(xmsg.GetData());
 char *szRecver = text.GetUID();
 char *szData = text.GetData();
 char *szSender = m_users.GetUser(sock)->GetUID();

 SOCKET userSock = m_users.GetSocket(szRecver);
 if (0 != userSock) // 用户在线!
 {
  // 转发数据
  CXEIM_Text xSendText(szSender, szData);
  XEIM_Message toSend("cmdline",xSendText.GetBuffer());
  // AfxMessageBox(toSend.GetBuffer());
  m_iocp.BuildPackageAndSend(m_users.GetSocket(szRecver), Job_UserData, toSend.GetBuffer());
/*  DWORD dwID = m_database.AddText(szSender, szRecver, szData);
  if (dwID)
   m_database.SetMessageRead(szRecver, dwID);*/
 // AfxMessageBox("用户在线!");
 }
 else // 用户不在线!
 {
 // m_database.AddText(szSender, szRecver, szData);
 // AfxMessageBox("用户不在线!");
 }
}

void CXeimDlg::ProcessForwardMessage(CXEIM_Text &text, SOCKET sock, LPCTSTR szMessage)
{
 //m_users.GetUser(pContext->m_Socket)->GetUID()
// CXEIM_Text xText(xmsg.GetData());
 char *szRecver = text.GetUID();
 char *szData = text.GetData();
 char *szSender = m_users.GetUser(sock)->GetUID();

// AfxMessageBox(szRecver);
 SOCKET userSock = m_users.GetSocket(szRecver);
 if (0 != userSock) // 用户在线!
 {
  // 转发数据
  CXEIM_Text xSendText(szSender, szData);
  XEIM_Message toSend((LPSTR)szMessage,xSendText.GetBuffer());
  // AfxMessageBox(toSend.GetBuffer());
  m_iocp.BuildPackageAndSend(m_users.GetSocket(szRecver), Job_UserData, toSend.GetBuffer());
 /* DWORD dwID = m_database.AddText(szSender, szRecver, szData);
  if (dwID)
   m_database.SetMessageRead(szRecver, dwID);*/
 // AfxMessageBox("用户在线!");
 }
 else // 用户不在线!
 {
 // m_database.AddText(szSender, szRecver, szData);
 // AfxMessageBox("用户不在线!");
 }
}

// 2010-5-1
// 蔡志华
// 聊天记录查询
void CXeimDlg::ProcessHistoryTree(SOCKET sock, TCHAR *szUser)
{
 char *szContact = m_database.GetContact(szUser);
 CString strContact = szContact;
 delete szContact;
 
 CString strTen;
 int nIdx = 0;
 while (-1 != nIdx)
 {
  nIdx = m_database.GetTenContact(strContact, strTen);
  char *szChunk;
  szChunk = m_database.GetContactChunk(szUser, (LPCTSTR)strTen);
  if (NULL != szChunk)
  {
   XEIM_Message toSend("historytree", szChunk);
   // AfxMessageBox(toSend.GetBuffer());
   m_iocp.BuildPackageAndSend(sock, Job_UserData, toSend.GetBuffer());
   delete szChunk;
  }
 } 
}
// 2010-5-1
// 蔡志华
// 聊天记录查询
void CXeimDlg::ProcessHistoryChat(SOCKET sock, LPCTSTR szOneUser,
          LPCTSTR szTwoUser, LPCTSTR szLastTime)
{
 char *szChat;

 szChat = m_database.GetChatText(szOneUser, szTwoUser, szLastTime);
 if (NULL == szChat)
 {
  return;
 }

 XEIM_Message toSend("historychat", szChat);
 //AfxMessageBox(szChat);
 m_iocp.BuildPackageAndSend(sock, Job_UserData, toSend.GetBuffer());

 delete szChat;
}

参考飞鸽传书:http://www.freeeim.com/

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/i_like_cpp/article/details/5556429

智能推荐

while循环&CPU占用率高问题深入分析与解决方案_main函数使用while(1)循环cpu占用99-程序员宅基地

文章浏览阅读3.8k次,点赞9次,收藏28次。直接上一个工作中碰到的问题,另外一个系统开启多线程调用我这边的接口,然后我这边会开启多线程批量查询第三方接口并且返回给调用方。使用的是两三年前别人遗留下来的方法,放到线上后发现确实是可以正常取到结果,但是一旦调用,CPU占用就直接100%(部署环境是win server服务器)。因此查看了下相关的老代码并使用JProfiler查看发现是在某个while循环的时候有问题。具体项目代码就不贴了,类似于下面这段代码。​​​​​​while(flag) {//your code;}这里的flag._main函数使用while(1)循环cpu占用99

【无标题】jetbrains idea shift f6不生效_idea shift +f6快捷键不生效-程序员宅基地

文章浏览阅读347次。idea shift f6 快捷键无效_idea shift +f6快捷键不生效

node.js学习笔记之Node中的核心模块_node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是-程序员宅基地

文章浏览阅读135次。Ecmacript 中没有DOM 和 BOM核心模块Node为JavaScript提供了很多服务器级别,这些API绝大多数都被包装到了一个具名和核心模块中了,例如文件操作的 fs 核心模块 ,http服务构建的http 模块 path 路径操作模块 os 操作系统信息模块// 用来获取机器信息的var os = require('os')// 用来操作路径的var path = require('path')// 获取当前机器的 CPU 信息console.log(os.cpus._node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是

数学建模【SPSS 下载-安装、方差分析与回归分析的SPSS实现(软件概述、方差分析、回归分析)】_化工数学模型数据回归软件-程序员宅基地

文章浏览阅读10w+次,点赞435次,收藏3.4k次。SPSS 22 下载安装过程7.6 方差分析与回归分析的SPSS实现7.6.1 SPSS软件概述1 SPSS版本与安装2 SPSS界面3 SPSS特点4 SPSS数据7.6.2 SPSS与方差分析1 单因素方差分析2 双因素方差分析7.6.3 SPSS与回归分析SPSS回归分析过程牙膏价格问题的回归分析_化工数学模型数据回归软件

利用hutool实现邮件发送功能_hutool发送邮件-程序员宅基地

文章浏览阅读7.5k次。如何利用hutool工具包实现邮件发送功能呢?1、首先引入hutool依赖<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version></dependency>2、编写邮件发送工具类package com.pc.c..._hutool发送邮件

docker安装elasticsearch,elasticsearch-head,kibana,ik分词器_docker安装kibana连接elasticsearch并且elasticsearch有密码-程序员宅基地

文章浏览阅读867次,点赞2次,收藏2次。docker安装elasticsearch,elasticsearch-head,kibana,ik分词器安装方式基本有两种,一种是pull的方式,一种是Dockerfile的方式,由于pull的方式pull下来后还需配置许多东西且不便于复用,个人比较喜欢使用Dockerfile的方式所有docker支持的镜像基本都在https://hub.docker.com/docker的官网上能找到合..._docker安装kibana连接elasticsearch并且elasticsearch有密码

随便推点

Python 攻克移动开发失败!_beeware-程序员宅基地

文章浏览阅读1.3w次,点赞57次,收藏92次。整理 | 郑丽媛出品 | CSDN(ID:CSDNnews)近年来,随着机器学习的兴起,有一门编程语言逐渐变得火热——Python。得益于其针对机器学习提供了大量开源框架和第三方模块,内置..._beeware

Swift4.0_Timer 的基本使用_swift timer 暂停-程序员宅基地

文章浏览阅读7.9k次。//// ViewController.swift// Day_10_Timer//// Created by dongqiangfei on 2018/10/15.// Copyright 2018年 飞飞. All rights reserved.//import UIKitclass ViewController: UIViewController { ..._swift timer 暂停

元素三大等待-程序员宅基地

文章浏览阅读986次,点赞2次,收藏2次。1.硬性等待让当前线程暂停执行,应用场景:代码执行速度太快了,但是UI元素没有立马加载出来,造成两者不同步,这时候就可以让代码等待一下,再去执行找元素的动作线程休眠,强制等待 Thread.sleep(long mills)package com.example.demo;import org.junit.jupiter.api.Test;import org.openqa.selenium.By;import org.openqa.selenium.firefox.Firefox.._元素三大等待

Java软件工程师职位分析_java岗位分析-程序员宅基地

文章浏览阅读3k次,点赞4次,收藏14次。Java软件工程师职位分析_java岗位分析

Java:Unreachable code的解决方法_java unreachable code-程序员宅基地

文章浏览阅读2k次。Java:Unreachable code的解决方法_java unreachable code

标签data-*自定义属性值和根据data属性值查找对应标签_如何根据data-*属性获取对应的标签对象-程序员宅基地

文章浏览阅读1w次。1、html中设置标签data-*的值 标题 11111 222222、点击获取当前标签的data-url的值$('dd').on('click', function() { var urlVal = $(this).data('ur_如何根据data-*属性获取对应的标签对象

推荐文章

热门文章

相关标签