chengweikang_ 发表于 2015-7-31 19:20:41

关于将业务逻辑做成Windows下的“服务”类型程序的问题

我今天下午搭建业务逻辑服务程序,考虑将业务逻辑的程序做成服务类型程序,程序搭建完成后,也以程序也以服务形式正式运行了,日志也打印了。
也在程序加入了AnyChatServerSDK等,也注册了相关的回调函数。但就是回调消息收不到!(如用户身份验证回调函数)
请问是不是不能将业务逻辑服务器做成服务类型的程序,就是在windows下服务栏中的一样,类似于SqlServer,oracle服务的类型。

#include "stdafx.h"
#include "JDCIMBizServer.h"
#include "AnyChatServerSDK.h"
#pragma comment(lib,"AnyChatServerSDK.lib")

#define SENDBUF_STYLE_SYSTEM        0                // 系统广播
#define SENDBUF_STYLE_ROOM                1                // 房间广播
#define SENDBUF_STYLE_USER                2                // 指定用户

#define TIMER_REFRESH_ONLINES        1                // 刷新在线用户数定时器

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 服务器应用程序消息回调函数定义
void CALLBACK OnServerAppMessageExCallBack(DWORD dwNotifyMessage, DWORD wParam, DWORD lParam, LPVOID lpUserValue)
{
        /*CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        if(dwNotifyMessage == BRAS_MESSAGE_CORESERVERCONN)
        {
                if(wParam == 0)
                        lpServerDlg->AppendLogString("Success connected with AnyChatCoreServer...");
                else
                        lpServerDlg->AppendLogString("Disconnected from the AnyChatCoreServer");
        }
        else if(dwNotifyMessage == BRAS_MESSAGE_RECORDSERVERCONN)
        {
                if(wParam == 0)
                {
                        CString strNotify;
                        strNotify.Format("Success connected with AnyChatRecordServer...(serverid:%d)", lParam);
                        lpServerDlg->AppendLogString(strNotify);
                }
                else
                {
                        CString strNotify;
                        strNotify.Format("Disconnected from the AnyChatRecordServer...(errorcode:%d, serverid:%d)", wParam, lParam);
                        lpServerDlg->AppendLogString(strNotify);
                }
        }
        else
        {
                CString strNotify;
                strNotify.Format("OnServerAppMessageExCallBack(dwNotifyMessage:%d, wParam:%d, lParam:%d)", dwNotifyMessage, wParam, lParam);
                lpServerDlg->AppendLogString(strNotify);
        }*/
}

/**
*        SDK定时器回调函数定义,上层应用可以在该回调中处理定时任务,而不需要额外开启线程,或是定时器
*        如果单独开启线程,或是注册Windows定时器,则必须考虑多线程同步的问题
*        而使用SDK的TimerEvent回调,则不需要考虑,因为定时器回调和别的回调函数均是顺序触发的
*/
void CALLBACK OnTimerEventCallBack(LPVOID lpUserValue)
{
//        CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
//        if(lpServerDlg)
//        {
////                lpServerDlg->AppendLogString("定时器事件");
//        }
}

// 用户身份验证回调函数定义
DWORD CALLBACK VerifyUserCallBack(IN LPCTSTR lpUserName,IN LPCTSTR lpPassword, OUT LPDWORD lpUserID, OUT LPDWORD lpUserLevel, OUT LPTSTR lpNickName,IN DWORD dwNCLen, LPVOID lpUserValue)
{
       
        CString strMsg;
        strMsg.Format(_T("VerifyUser(%s - %s) --> userid(%d)"),lpUserName,lpPassword,(int)*lpUserID);
        WriteToLog(strMsg.GetBuffer(0));

        /*static DWORD dwUserIdSeed = 1;
        *lpUserID = dwUserIdSeed++;

        CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        if(lpServerDlg && lpServerDlg->m_bShowUserLog)
        {
                CString strMsg;
                strMsg.Format(_T("VerifyUser(%s - %s) --> userid(%d)"),lpUserName,lpPassword,(int)*lpUserID);
                lpServerDlg->AppendLogString(strMsg);
        }*/
        return 0;
}
// 用户申请进入房间回调函数定义
DWORD CALLBACK PrepareEnterRoomCallBack(DWORD dwUserId, DWORD dwRoomId, LPCTSTR lpRoomName,LPCTSTR lpPassword, LPVOID lpUserValue)
{
        /*CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        if(lpServerDlg && lpServerDlg->m_bShowUserLog)
        {
                CString strMsg;
                strMsg.Format(_T("PrepareEnterRoom(dwUserId:%d - dwRoomId:%d)"),(int)dwUserId,(int)dwRoomId);
                lpServerDlg->AppendLogString(strMsg);
        }*/
        return 0;
}
// 用户登录成功回调函数定义
void CALLBACK OnUserLoginActionCallBack(DWORD dwUserId, LPCTSTR szUserName, DWORD dwLevel, LPCTSTR szIpAddr, LPVOID lpUserValue)
{
        //CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        //if(!lpServerDlg)
        //        return;

        //// 获取在线用户列表
        //DWORD dwOnlineUserCount = 0;
        //DWORD* lpOnlineUserIdArray = NULL;
        //BRAS_GetOnlineUsers(-1, NULL, dwOnlineUserCount);                        // 第一次查询只是获取在线用户数,为后面分配ID空间做准备
        //if(dwOnlineUserCount)
        //{
        //        lpOnlineUserIdArray = (DWORD*)malloc(dwOnlineUserCount * sizeof(DWORD));
        //        if(!lpOnlineUserIdArray)
        //                return;
        //        BRAS_GetOnlineUsers(-1, lpOnlineUserIdArray, dwOnlineUserCount);                // 第二次查询获取实际的ID列表
        //}
        //
        //// 添加用户分组
        //int iGroupId = 1;
        //BRAS_UserInfoControl(dwUserId, BRAS_USERINFO_CTRLCODE_ADDGROUP, iGroupId, 0, "我的好友");        // 用户名+密码方式登录的用户
        //iGroupId = 2;
        //BRAS_UserInfoControl(dwUserId, BRAS_USERINFO_CTRLCODE_ADDGROUP, iGroupId, 0, "在线游客");        // 密码为空的用户

        //// 将当前所有在线用户添加为自己的好友
        //if(lpOnlineUserIdArray)
        //{
        //        DWORD dwOffset = 0;
        //        while(dwOffset < dwOnlineUserCount)
        //        {
        //                DWORD dwOtherUserId = lpOnlineUserIdArray;
        //                if(dwOtherUserId != dwUserId)
        //                        BRAS_UserInfoControl(dwUserId, BRAS_USERINFO_CTRLCODE_ADDFRIEND, dwOtherUserId, 0, "");
        //                dwOffset++;
        //        }
        //}

        //// 设置好友与分组的关系(即好友属于哪一个分组)
        //iGroupId = 1;
        //if(lpOnlineUserIdArray)
        //{
        //        DWORD dwOffset = 0;
        //        while(dwOffset < dwOnlineUserCount)
        //        {
        //                DWORD dwOtherUserId = lpOnlineUserIdArray;
        //                if(dwOtherUserId != dwUserId)
        //                {
        //                        iGroupId = (dwOtherUserId > 0) ? 1 : 2;                // 游客密码为空,userid由核心服务器分配,为负数
        //                        BRAS_UserInfoControl(dwUserId, BRAS_USERINFO_CTRLCODE_SETGROUPRELATION, iGroupId, dwOtherUserId, "");
        //                }
        //                dwOffset++;
        //        }
        //}

        //// 设置当前用户信息(用户资料,客户端可以通过API:BRAC_GetUserInfo来获取这些信息)
        //int iInfoId = 1;        // InfoId由业务层自己定义
        //BRAS_SetUserInfo(dwUserId, iInfoId, szUserName, 0);
        //iInfoId = 2;
        //BRAS_SetUserInfo(dwUserId, iInfoId, szIpAddr, 0);
        //iInfoId = 3;
        //BRAS_SetUserInfo(dwUserId, iInfoId, "我的签名", 0);
        //iInfoId = 4;
        //CHAR szImageId = {0};
        //_snprintf(szImageId, sizeof(szImageId), "%d", dwUserId%10 + 1);
        //BRAS_SetUserInfo(dwUserId, iInfoId, szImageId, 0);                // 随机分配一个图像ID

        //// 将本地用户添加为其它用户的好友列表中
        //if(lpOnlineUserIdArray)
        //{
        //        DWORD dwOffset = 0;
        //        while(dwOffset < dwOnlineUserCount)
        //        {
        //                DWORD dwOtherUserId = lpOnlineUserIdArray;
        //                if(dwOtherUserId != dwUserId)
        //                {
        //                        // 添加好友
        //                        BRAS_UserInfoControl(dwOtherUserId, BRAS_USERINFO_CTRLCODE_ADDFRIEND, dwUserId, 0, "");
        //                        // 关联好友分组
        //                        iGroupId = (dwUserId > 0) ? 1 : 2;
        //                        BRAS_UserInfoControl(dwOtherUserId, BRAS_USERINFO_CTRLCODE_SETGROUPRELATION, iGroupId, dwUserId, "");
        //                        // 下发同步指令,将新设置的好友同步给客户端
        //                        BRAS_UserInfoControl(dwOtherUserId, BRAS_USERINFO_CTRLCODE_SYNCDATA,0, 0, "");
        //                }
        //                dwOffset++;
        //        }
        //}

        //// 下发同步指令,将前面设置的资料同步给当前客户端
        //BRAS_UserInfoControl(dwUserId, BRAS_USERINFO_CTRLCODE_SYNCDATA,0, 0, "");

        //if(lpServerDlg->m_bShowUserLog)
        //{
        //        CString strMsg;
        //        strMsg.Format(_T("OnUserLoginAction(dwUserId:%d - Name:%s)"),(int)dwUserId,szUserName);
        //        lpServerDlg->AppendLogString(strMsg);
        //}

        //if(lpOnlineUserIdArray)
        //        free(lpOnlineUserIdArray);
}
// 用户注销回调函数定义
void CALLBACK OnUserLogoutActionExCallBack(DWORD dwUserId, DWORD dwErrorCode, LPVOID lpUserValue)
{
        //CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        //if(!lpServerDlg)
        //        return;

        //// 核心服务器会通知其它用户(如果是好友),提示好友下线,不需要业务服务器干预

        //if(lpServerDlg->m_bShowUserLog)
        //{
        //        CString strMsg;
        //        strMsg.Format(_T("OnUserLogoutAction(dwUserId:%d, dwErrorCode:%d)"),(int)dwUserId, dwErrorCode);
        //        lpServerDlg->AppendLogString(strMsg);
        //}
}
// 用户进入房间回调函数定义
void CALLBACK OnUserEnterRoomActionCallBack(DWORD dwUserId, DWORD dwRoomId, LPVOID lpUserValue)
{
        /*CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        if(lpServerDlg && lpServerDlg->m_bShowUserLog)
        {
                CString strMsg;
                strMsg.Format(_T("OnUserEnterRoomAction(dwUserId:%d - dwRoomId:%d)"),(int)dwUserId,(int)dwRoomId);
                lpServerDlg->AppendLogString(strMsg);
        }*/
}
// 用户离开房间回调函数定义
void CALLBACK OnUserLeaveRoomActionCallBack(DWORD dwUserId, DWORD dwRoomId, LPVOID lpUserValue)
{
        /*CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        if(lpServerDlg && lpServerDlg->m_bShowUserLog)
        {
                CString strMsg;
                strMsg.Format(_T("OnUserLeaveRoomAction(dwUserId:%d - dwRoomId:%d)"),(int)dwUserId,(int)dwRoomId);
                lpServerDlg->AppendLogString(strMsg);
        }*/
}
// 上层业务自定义数据回调函数定义
void CALLBACK OnRecvUserFilterDataCallBack(DWORD dwUserId, BYTE* lpBuf, DWORD dwLen, LPVOID lpUserValue)
{
        /*CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        if(lpServerDlg && lpServerDlg->m_bShowUserLog)
        {
                CString strMsg;
                strMsg.Format(_T("OnRecvUserFilterData(dwUserId:%d - Buf:%s)"),(int)dwUserId,lpBuf);
                lpServerDlg->AppendLogString(strMsg);
        }*/
}
// 收到用户文字聊天通信数据回调函数定义
void CALLBACK OnRecvUserTextMsgCallBack(DWORD dwRoomId, DWORD dwSrcUserId, DWORD dwTarUserId, BOOL bSecret, LPCTSTR lpTextMessage, DWORD dwLen, LPVOID lpUserValue)
{
        /*CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        if(lpServerDlg && lpServerDlg->m_bShowUserLog)
        {
                CString strMsg;
                strMsg.Format(_T("OnRecvUserTextMsg(dwRoomId:%d, dwSrcUserId:%d, dwTarUserId:%d - Buf:%s)"),(int)dwRoomId,(int)dwSrcUserId,(int)dwTarUserId,lpTextMessage);
                lpServerDlg->AppendLogString(strMsg);
        }*/
}
// 透明通道数据回调函数定义
void CALLBACK OnTransBufferCallBack(DWORD dwUserId, LPBYTE lpBuf, DWORD dwLen, LPVOID lpUserValue)
{
        /*CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        if(lpServerDlg && lpServerDlg->m_bShowUserLog)
        {
                CString strMsg;
                strMsg.Format(_T("OnTransBufferCallBack(dwUserId:%d - BufLen:%d)"),(int)dwUserId,dwLen);
                lpServerDlg->AppendLogString(strMsg);
        }*/
}
// 透明通道数据扩展回调函数定义
void CALLBACK OnTransBufferExCallBack(DWORD dwUserId, LPBYTE lpBuf, DWORD dwLen, DWORD wParam, DWORD lParam, DWORD dwTaskId, LPVOID lpUserValue)
{
        /*CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        if(lpServerDlg && lpServerDlg->m_bShowUserLog)
        {
                CString strMsg;
                strMsg.Format(_T("OnTransBufferExCallBack(dwUserId:%d - BufLen:%d - wParam:%d - lParam:%d - dwTaskId:%d)"),(int)dwUserId,dwLen, wParam, lParam, dwTaskId);
                lpServerDlg->AppendLogString(strMsg);
        }*/
}
// 文件传输回调函数定义
void CALLBACK OnTransFileCallBack(DWORD dwUserId, LPCTSTR lpFileName, LPCTSTR lpTempFilePath, DWORD dwFileLength, DWORD wParam, DWORD lParam, DWORD dwTaskId, LPVOID lpUserValue)
{
        //CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        //if(lpServerDlg && lpServerDlg->m_bShowUserLog)
        //{
        //        CString strMsg;
        //        strMsg.Format(_T("OnTransFileCallBack(dwUserId:%d, PathName:%s - wParam:%d - lParam:%d - dwTaskId:%d)"),(int)dwUserId, lpFileName, wParam, lParam, dwTaskId);
        //        lpServerDlg->AppendLogString(strMsg);
        //}
}
// 服务器录像回调函数定义(扩展)
void CALLBACK OnServerRecordEx_CallBack(DWORD dwUserId, LPCTSTR lpFileName, DWORD dwElapse, DWORD dwFlags, DWORD dwParam, LPCTSTR lpUserStr, DWORD dwRecordServerId, LPVOID lpUserValue)
{
        //CAnyChatCallCenterServerDlg* lpServerDlg = (CAnyChatCallCenterServerDlg*)lpUserValue;
        //if(lpServerDlg)
        //{
        //        CString strMsg;
        //        BOOL bSnapShotType = !!(dwFlags & ANYCHAT_RECORD_FLAGS_SNAPSHOT);
        //        strMsg.Format(_T("OnServerRecordExCallBack(type:%s dwUserId:%d, dwParam:%d, dwElapse:%d, FileName:%s, UserStr:%s)"), bSnapShotType?_T("SnapShot"):_T("Record"), (int)dwUserId, dwParam, dwElapse, lpFileName, lpUserStr);
        //        lpServerDlg->AppendLogString(strMsg);
        //}
}

/****************************************************************************************
* 记录日志.
* @param                char*
* @return                        int
* @note                        在需要记录日志的地方传入所需要记录的字符串即可.
* @author                        WeiKangC
* @date                        2015/07/31
****************************************************************************************/
int WriteToLog(char* str)
{
   FILE* log;
   log = fopen(LOGFILE, "a+");
   if (log == NULL){
          OutputDebugString("Log file open failed.");
      return -1;
   }
   fprintf(log, "%s\n", str);
   fclose(log);
   return 0;
}

/****************************************************************************************
* 判断服务是否已经被安装.
* @param                void
* @return                        BOOL
* @note                        判断服务是否已经被安装,在需要的地方调用即可。
* @author                        WeiKangC
* @date                        2015/07/31
*****************************************************************************************/
BOOL IsInstalled()
{
    BOOL bResult = FALSE;

        //打开服务控制管理器
    SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);

    if (hSCM != NULL)
    {
                //打开服务
      SC_HANDLE hService = ::OpenService(hSCM, szServiceName, SERVICE_QUERY_CONFIG);
      if (hService != NULL)
      {
            bResult = TRUE;
            ::CloseServiceHandle(hService);
      }
      ::CloseServiceHandle(hSCM);
    }
    return bResult;
}
/****************************************************************************************
* 安装服务函数.
* @param                void
* @return                        BOOL
* @note                        安装服务函数,在需要的地方调用即可。
* @author                        WeiKangC
* @date                        2015/07/31
*****************************************************************************************/
BOOL Install()
{
    if (IsInstalled())
      return TRUE;

        //打开服务控制管理器
    SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (hSCM == NULL)
    {
      MessageBox(NULL, _T("Couldn't open service manager"), szServiceName, MB_OK);
      return FALSE;
    }

    // Get the executable file path
    TCHAR szFilePath;
    ::GetModuleFileName(NULL, szFilePath, MAX_PATH);

        //创建服务
    SC_HANDLE hService = ::CreateService(
      hSCM, szServiceName, szServiceName,
      SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
      SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
      szFilePath, NULL, NULL, _T(""), NULL, NULL);

    if (hService == NULL)
    {
      ::CloseServiceHandle(hSCM);
      MessageBox(NULL, _T("Couldn't create service"), szServiceName, MB_OK);
      return FALSE;
    }

    ::CloseServiceHandle(hService);
    ::CloseServiceHandle(hSCM);
    return TRUE;
}

/****************************************************************************************
* 删除服务函数.
* @param                void
* @return                        BOOL
* @note                        删除服务函数,在需要的地方调用即可。
* @author                        WeiKangC
* @date                        2015/07/31
*****************************************************************************************/
BOOL Uninstall()
{
    if (!IsInstalled())
      return TRUE;

    SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (hSCM == NULL)
    {
      MessageBox(NULL, _T("Couldn't open service manager"), szServiceName, MB_OK);
      return FALSE;
    }

    SC_HANDLE hService = ::OpenService(hSCM, szServiceName, SERVICE_STOP | DELETE);

    if (hService == NULL)
    {
      ::CloseServiceHandle(hSCM);
      MessageBox(NULL, _T("Couldn't open service"), szServiceName, MB_OK);
      return FALSE;
    }
    SERVICE_STATUS status;
    ::ControlService(hService, SERVICE_CONTROL_STOP, &status);

        //删除服务
    BOOL bDelete = ::DeleteService(hService);
    ::CloseServiceHandle(hService);
    ::CloseServiceHandle(hSCM);

    if (bDelete)
      return TRUE;

    WriteToLog(_T("Service could not be deleted"));
    return FALSE;
}

/****************************************************************************************
* 初始化服务管理器服务函数.
* @param                void
* @return                        int
* @note                        初始化服务管理器服务函数,在需要的地方调用即可。
* @author                        WeiKangC
* @date                        2015/07/31
*****************************************************************************************/
int InitService()
{
        // 设置服务器应用程序消息回调函数
        BRAS_SetOnServerAppMessageExCallBack(OnServerAppMessageExCallBack);
        // 设置SDK定时器回调函数
        BRAS_SetTimerEventCallBack(1000,OnTimerEventCallBack);
        // 设置用户身份验证回调函数
        BRAS_SetVerifyUserCallBack(VerifyUserCallBack);
        // 设置用户申请进入房间回调函数
        BRAS_SetPrepareEnterRoomCallBack(PrepareEnterRoomCallBack);
        // 设置用户登录成功回调函数
        BRAS_SetOnUserLoginActionCallBack(OnUserLoginActionCallBack);
        // 设置用户注销回调函数(扩展)
        BRAS_SetOnUserLogoutActionExCallBack(OnUserLogoutActionExCallBack);
        // 设置用户进入房间回调函数
        BRAS_SetOnUserEnterRoomActionCallBack(OnUserEnterRoomActionCallBack);
        // 设置用户离开房间回调函数
        BRAS_SetOnUserLeaveRoomActionCallBack(OnUserLeaveRoomActionCallBack);
        // 设置用户上层业务自定义数据回调函数
        BRAS_SetOnRecvUserFilterDataCallBack(OnRecvUserFilterDataCallBack);
        // 用户文字聊天通信数据回调函数
        BRAS_SetOnRecvUserTextMsgCallBack(OnRecvUserTextMsgCallBack);
        // 设置透明通道数据回调函数
        BRAS_SetOnTransBufferCallBack(OnTransBufferCallBack);
        // 设置透明通道数据扩展回调函数
        BRAS_SetOnTransBufferExCallBack(OnTransBufferExCallBack);
        // 设置文件传输回调函数
        BRAS_SetOnTransFileCallBack(OnTransFileCallBack);
        // 设置服务器录像回调函数
        BRAS_SetCallBack(BRAS_CBTYPE_SERVERRECORDEX, OnServerRecordEx_CallBack);

        BRAS_InitSDK(0);

        SetTimer(NULL,TIMER_REFRESH_ONLINES, 1000, NULL);

        OutputDebugString("Monitoring startedxxxxx.");
        int result;
        result = WriteToLog("Monitoring startedxxxxxxx.");
        return(result);
}

/****************************************************************************************
* ControlHandler .
* @param                DWORD
* @return                        void
* @note                        ControlHandler 。
* @author                        WeiKangC
* @date                        2015/07/31
*****************************************************************************************/
void ControlHandler(DWORD request)
{
   switch(request)
   {
      case SERVICE_CONTROL_STOP:
               OutputDebugString("Monitoring stopped.");
         WriteToLog("Monitoring stopped.");

         ServiceStatus.dwWin32ExitCode = 0;
         ServiceStatus.dwCurrentState = SERVICE_STOPPED;
         SetServiceStatus (hStatus, &ServiceStatus);
         return;
               break;
      case SERVICE_CONTROL_SHUTDOWN:
               OutputDebugString("Monitoring stopped.");
         WriteToLog("Monitoring stopped.");

         ServiceStatus.dwWin32ExitCode = 0;
         ServiceStatus.dwCurrentState = SERVICE_STOPPED;
         SetServiceStatus (hStatus, &ServiceStatus);
         return;
               break;
          case SERVICE_CONTROL_PAUSE:
                  OutputDebugString("Monitoring pause.");
                  WriteToLog("Monitoring pause.");

                  ServiceStatus.dwWin32ExitCode = 0 ;
                  ServiceStatus.dwCurrentState= SERVICE_PAUSED;
                  SetServiceStatus(hStatus,&ServiceStatus);
                  return;
                  break;
          case SERVICE_CONTROL_CONTINUE:
                  OutputDebugString("Monitoring running.");
                  WriteToLog("Monitoring running.");

                  ServiceStatus.dwWin32ExitCode = 0 ;
                  ServiceStatus.dwCurrentState= SERVICE_RUNNING;
                  SetServiceStatus(hStatus,&ServiceStatus);
                  return ;
                  break;
      default:
         break;
    }
    SetServiceStatus (hStatus, &ServiceStatus);

    return;
}
/****************************************************************************************
* ServiceMain
* @param                DWORD
* @return                        void
* @note                        Service Main Control Function
* @author                        WeiKangC
* @date                        2015/07/31
*****************************************************************************************/
void ServiceMain(int argc, char** argv)
{   
   ServiceStatus.dwServiceType                  =   SERVICE_WIN32;
   ServiceStatus.dwCurrentState       =   SERVICE_START_PENDING;
   ServiceStatus.dwControlsAccepted   =   SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_SHUTDOWN|SERVICE_ACCEPT_PAUSE_CONTINUE;
   ServiceStatus.dwWin32ExitCode          =   NO_ERROR;
   ServiceStatus.dwServiceSpecificExitCode = NO_ERROR;
   ServiceStatus.dwCheckPoint = 0;
   ServiceStatus.dwWaitHint = 30;

   hStatus = RegisterServiceCtrlHandler("JDCIMBizServer",
           (LPHANDLER_FUNCTION)ControlHandler);

   if (hStatus ==
           (SERVICE_STATUS_HANDLE)0)
   {
      WriteToLog("Registering Control Handler failed!");
      return;
   }

   int error = InitService();
   if (error)
   {
          // Initialization failed
      ServiceStatus.dwCurrentState =SERVICE_STOPPED;
      ServiceStatus.dwWin32ExitCode = -1;
      SetServiceStatus(hStatus, &ServiceStatus);
      return;
   }

   // We report the running status to SCM.
   ServiceStatus.dwCurrentState                           = SERVICE_RUNNING;
   ServiceStatus.dwCheckPoint                           = 0;
   ServiceStatus.dwWaitHint                                   = 0;
   ServiceStatus.dwWin32ExitCode                   = NO_ERROR;
   ServiceStatus.dwServiceSpecificExitCode = NO_ERROR;
   SetServiceStatus (hStatus, &ServiceStatus);

   MEMORYSTATUS memory = { 0 };

   // The worker loop of a service
   while (ServiceStatus.dwCurrentState
      == SERVICE_RUNNING)
   {
          //char buffer = { 0 };
      //GlobalMemoryStatus(&memory);
      //sprintf(buffer, "%d", memory.dwAvailPhys);

      //OutputDebugString(buffer);
      //int result = WriteToLog(buffer);
   // if (result)
   // {
   //    ServiceStatus.dwCurrentState= SERVICE_STOPPED;
   //    ServiceStatus.dwWin32ExitCode = -1;
   //    SetServiceStatus(hStatus,&ServiceStatus);
   //    return;
   // }
   // Sleep(SLEEP_TIME);
   }
   return;
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
        int nRetCode = 0;

        SERVICE_TABLE_ENTRY ServiceTable;
        ServiceTable.lpServiceName = "JDCIMBizServer";
        ServiceTable.lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;

        ServiceTable.lpServiceName = NULL;
        ServiceTable.lpServiceProc = NULL;

        // Start the control dispatcher thread for our service
        StartServiceCtrlDispatcher(ServiceTable);

        return nRetCode;
}
页: [1]
查看完整版本: 关于将业务逻辑做成Windows下的“服务”类型程序的问题