Ejemplo n.º 1
0
void C_AreaEvent::PushEvent( Poco::Net::StreamSocket& sktClient, LPCTSTR pszMac )
{
	m_PushedVecMutex.lock();
	for (EventList::iterator it = m_vecPushedEvent.begin(); it != m_vecPushedEvent.end(); )
	{
		if(CompareTime((*it)->szEndTime.c_str() , GetCurrTime().c_str()) < 0)
			it = m_vecPushedEvent.erase(it);
		else
			++it;
	}
	m_PushedVecMutex.unlock();

	tstring szAreaid = m_DBOperate.GetAreaidByMac(pszMac);
	if(szAreaid.compare(_T("")) == 0)
		return;

	m_PushedVecMutex.lock();
	for (EventList::iterator itor = m_vecPushedEvent.begin(); itor != m_vecPushedEvent.end(); ++itor)
	{
		if((*itor)->szAreaId == szAreaid)
		{
			tstring szJson = GetJsonText(*itor);
			sktClient.sendBytes(szJson.c_str(), szJson.length());
		}
	}
	m_PushedVecMutex.unlock();
}
BOOL C_NetCmdCaptureScreenshot::HandleRequest(Poco::Net::StreamSocket& sktClient, LPCTSTR pszCmdStream, 
	C_DBOperate& DBOperate, LPCTSTR pszMac)
{
	tstring szCmdCapture = _T("{\"type\":\"request\",\"cmd\":\"capture screenshot\", \"parameters\":null}\n");

	if(! m_NetCmdDecomposer.Decompose(pszCmdStream) )
		return FALSE;

	for (DWORD dwCount = 0 ; dwCount < m_NetCmdDecomposer.GetArraySize(_T("idArray")) ; dwCount ++)
	{
		tstring szMac = m_NetCmdDecomposer.GetValueByIndex(_T("idArray"), dwCount);

		if (szMac.compare(_T("")) == 0)
			continue;

		Poco::Net::StreamSocket* psktClient = C_ClientMac2Socket::GetInstance()->FindSocketByMacAddr(szMac.c_str());
		if (psktClient != NULL)
			psktClient->sendBytes(szCmdCapture.c_str(),szCmdCapture.length());
		//{
		//	SocketList ReadList, WriteList, ExceptList;
		//	WriteList.push_back(sktClient);
		//	if (Poco::Net::Socket::select(ReadList, WriteList, ExceptList, Poco::Timespan(10,0)) > 0)
		//	{
		//		sktClient->sendBytes(szCmdCapture.c_str(),szCmdCapture.length());
		//	}
		//	WriteList.clear();
		//}	
	}

	return TRUE;
}
int main()
{
	Poco::DateTime now;
	char szClientName[256] = { 0, };
	sprintf_s(szClientName, 256 - 1, "(%d-%d)", now.second(), now.millisecond());
		
	std::cout << "clinet(" << szClientName << ") 서버에 연결 시도..." << std::endl;
	Poco::Net::StreamSocket ss;

	try
	{
		ss.connect(Poco::Net::SocketAddress("localhost", PORT));

		for (int i = 0; i < 7; ++i)
		{
			char szMessage[256] = { 0, };
			sprintf_s(szMessage, 256 - 1, "%d, Send Message From %s", i, szClientName);
			auto nMsgLen = (int)strnlen_s(szMessage, 256 - 1);

			ss.sendBytes(szMessage, nMsgLen);

			std::cout << "서버에 보낸 메시지: " << szMessage << std::endl;


			char buffer[256] = { 0, };
			auto len = ss.receiveBytes(buffer, sizeof(buffer));

			if (len <= 0)
			{
				std::cout << "서버와 연결이 끊어졌습니다" << std::endl;
				break;
			}

			std::cout << "서버로부터 받은 메시지: " << buffer << std::endl;

			Poco::Thread::sleep(256);
		}

		ss.close();
	}
	catch (Poco::Exception& exc)
	{
		std::cout << "서버 접속 실패: " << exc.displayText() << std::endl;
	}
		
	getchar();
	return 0;
}
Ejemplo n.º 4
0
int main()
{
    Poco::Net::SocketAddress address = Poco::Net::SocketAddress("localhost", 10045);

    Poco::Net::StreamSocket *sock = new Poco::Net::StreamSocket(address);
    sock->setNoDelay(true);
    sock->setBlocking(true);
    sock->setReceiveTimeout(Poco::Timespan(3, 0));
    sock->setSendTimeout(Poco::Timespan(3, 0));

    for(;;) {
        char message[8];
        sock->sendBytes("ping", 5);
        sock->sendBytes("ping", 5);
        sock->receiveBytes(message, 5);
        printf("%s\n", message);
    }
}
int main()
{
	std::cout << "서버 초기화 시작" << std::endl;

	Poco::Net::SocketAddress server_add(PORT);
	Poco::Net::ServerSocket server_sock(server_add);
	
	std::cout << "서버 초기화 완료. 클라이언트 접속 대기 중..." << std::endl;


	while (true)
	{
		Poco::Net::StreamSocket ss = server_sock.acceptConnection();
		try
		{
			char buffer[256] = { 0, };
			int n = ss.receiveBytes(buffer, sizeof(buffer));
			std::cout << "클라이언트에서 받은 메시지: " << buffer << std::endl;
				
			while (n > 0)
			{
				char szSendMessage[256] = { 0, };
				sprintf_s(szSendMessage, 128 - 1, "Re:%s", buffer);
				int nMsgLen = strnlen_s(szSendMessage, 256 - 1);

				ss.sendBytes(szSendMessage, nMsgLen);


				n = ss.receiveBytes(buffer, sizeof(buffer));
				std::cout << "클라이언트에서 받은 메시지: " << buffer << std::endl;
			}

			std::cout << "클라이언트와 연결이 끊어졌습니다" << std::endl;				
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "EchoServer: " << exc.displayText() << std::endl;
		}
	}

	getchar();
	return 0;
}
Ejemplo n.º 6
0
void C_AreaEvent::DoUpdateEventList()
{
	while (::WaitForSingleObject(m_hStopEvent, 0) != WAIT_OBJECT_0)
	{
		m_PushVecMutex.lock();
		for (EventList::iterator it = m_vecEventList.begin(); it != m_vecEventList.end();)
		{
			tstring szAreaid = (*it)->szAreaId;
			tstring szStartTime = (*it)->szStartTime;

			if(CompareTime(szStartTime.c_str(), GetCurrTime().c_str()) <= 0 )
			{
				tstring szJson = GetJsonText(*it);
				StringVector vecMacList;
				m_DBOperate.GetMacListByAreaid(vecMacList, szAreaid.c_str());

				for (StringVector::iterator itor = vecMacList.begin(); itor != vecMacList.end(); ++itor)
				{
					Poco::Net::StreamSocket* psktClient = C_ClientMac2Socket::GetInstance()->FindSocketByMacAddr((*itor).c_str());
					if (psktClient != NULL)
						psktClient->sendBytes(szJson.c_str(), szJson.length());
				}
				m_PushedVecMutex.lock();
				m_vecPushedEvent.push_back(*it);
				m_PushedVecMutex.unlock();

				it = m_vecEventList.erase(it);
			}
			else
				++it;
		}
		m_PushVecMutex.unlock();

		Sleep(10000);//10s
	}
}
	void NetworkTransmitTaskTCP::execute(unsigned long timeDelta)
	{
		memUInt dataSize;
		std::list<Poco::AutoPtr<NetworkMessage> >::const_iterator iter;

		rwLock.writeLock();

		if (state != TS_RUNNING)
		{
			state = TS_RUNNING;
		}

		// Construct the list of NetworkMessages to transmit
		pBehaviour->update();

		const std::list<Poco::AutoPtr<NetworkMessage> >& networkMessageQueue = pBehaviour->getMessagesToTransmit();
		rwLock.unlock();

		for (iter = networkMessageQueue.begin(); iter != networkMessageQueue.end(); ++iter)
		{
			const Poco::AutoPtr<NetworkMessage>& message = *iter;

			// Ensure that the message is not NULL
			if (message.get() == NULL)
			{
				LOG(EngineLog::LM_WARNING, "NetworkTransmitTaskTCP::execute(): message is NULL.");
				return;
			}

			// Serialize the message into pSendBuffer
			dataSize = 0;
			try
			{
				dataSize = message->serialize(pSendBuffer, Constants::NETWORK_TRANSMIT_BUFFER_SIZE, Serializable::ST_NETWORK);
			}
			catch (Exception& e)
			{
				LOG(EngineLog::LM_ERROR, "NetworkTransmitTaskTCP::execute(): error serialising message for transmission: " << e.what());
			}

			// Transmit the serialised message to the specified host.
			if (dataSize != 0)
			{
				try
				{
					HostRecord record;
					Poco::Net::StreamSocket socket;

					if (NetworkManager::getSingleton().getConnectedHost(message->getDestination().toString(), record))
					{
						socket = record.getSocket();
					}
					else
					{
						socket.connect(Poco::Net::SocketAddress(message->getDestination(), Constants::NETWORK_LISTEN_PORT));
						socket.setKeepAlive(true);
						socket.setBlocking(false);
						// Add the host to the list of connected hosts in the network manager
						record = NetworkManager::getSingleton().createHostRecord(message->getDestination().toString());
						record.setSocket(socket);
						NetworkManager::getSingleton().addConnectedHost(record);
					}
					// Do not send with invalid sockets
					if ((socket.impl() != NULL) && (socket.impl()->sockfd() != POCO_INVALID_SOCKET))
					{
						socket.setKeepAlive(true);
						socket.sendBytes(pSendBuffer, dataSize);
					}
				}
				catch (Poco::Exception& e)
				{
					LOG(EngineLog::LM_ERROR, "NetworkTransmitTaskTCP::execute(): error transmitting message: " << e.message());
				}
			}
		}

		Poco::ScopedRWLock lock(rwLock, false);

		pBehaviour->clearListOfMessagesToTransmit();
	}
Ejemplo n.º 8
0
/**
This function attempts to retrieve a Json value from a URL via an http request.  If the request/parsing is successful, the retrieved Json value is stored in the given buffer.  This function is not particularly efficient, so it might be worth considering streamlining the application if that is a concern.
@param inputURL: The URL to retrieve the Json object from
@param inputValueBuffer: The object to store the retrieved value in
@param inputTimeoutDurationInMicroseconds: How long to wait for the value to be return in microseconds
@return: True if successful and false otherwise
*/
bool pylongps::getJsonValueFromURL(const std::string &inputURL, Json::Value &inputValueBuffer, int64_t inputTimeoutDurationInMicroseconds)
{

try
{
Poco::Timestamp startTime;
Poco::Timestamp timeoutTimepoint = startTime+((Poco::Timestamp::TimeDiff) inputTimeoutDurationInMicroseconds);

//Parse URI
Poco::URI url(inputURL);

Poco::Net::HostEntry host;
host = Poco::Net::DNS::hostByName(url.getHost());

if(host.addresses().size() == 0)
{//No IP address for host, so exit silently
return false;
}


Poco::Net::StreamSocket connectionSocket;

connectionSocket.connect(Poco::Net::SocketAddress(host.addresses()[0], 80));

connectionSocket.setReceiveTimeout(timeoutTimepoint-Poco::Timestamp());

Poco::Net::HTTPRequest getRequest("GET", url.getPathAndQuery(), "HTTP/1.1");
getRequest.setHost(url.getHost());

std::stringstream serializedHeader;
getRequest.write(serializedHeader);

connectionSocket.sendBytes(serializedHeader.str().c_str(), serializedHeader.str().size());

std::array<char, 1024> receiveBuffer;
int amountOfDataReceived = 0;
std::string receivedData;
while(Poco::Timestamp() < timeoutTimepoint)
{
amountOfDataReceived = connectionSocket.receiveBytes(receiveBuffer.data(), receiveBuffer.size());

if(amountOfDataReceived == 0)
{
break;
}

receivedData += std::string(receiveBuffer.data(), amountOfDataReceived);

if(receivedData.find("}") != std::string::npos)
{
break;
}
}

if(receivedData.find("{") == std::string::npos)
{
return false;
}

receivedData = receivedData.substr(receivedData.find("{"));

Json::Reader reader;

if(reader.parse(receivedData, inputValueBuffer) != true)
{
return false; //Couldn't parse JSON
}

return true;
}
catch(const std::exception &inputException)
{
return false;
}

}
Ejemplo n.º 9
0
void AcceptThread::run() {
	Poco::Net::StreamSocket StrmSock;

	#ifndef _DEBUG
	string sNewConnectionIP;
	vector<std::pair<string,Poco::Timestamp::TimeDiff>> vConnections,vBannedIPs;
	vector<	std::pair<
						string,  /* IP */
						std::pair<
								Timestamp::TimeDiff, /* Ban time */
								Timestamp::TimeDiff /* Entry reset */
								 >
					>
	       > vBanLenght;

	Poco::Stopwatch Timer;
	Poco::Timestamp::TimeDiff lowest,actual;
	
	int x,i;
	short iCount;
	bool fExit;
	
	Timer.start();
	#endif

	_iThreadStatus = FC_THREADSTATUS_RUNNING;
	while(_iThreadStatus==FC_THREADSTATUS_RUNNING) {
		try {
			_ServerSock.listen();
			StrmSock = _ServerSock.acceptConnection(); 
			
			#ifndef _DEBUG
			cutOffPort(StrmSock.peerAddress().toString(),sNewConnectionIP);
			/* Check banlist */
			if (!vBannedIPs.empty()) {
				actual = (Timer.elapsed()/1000);
				fExit = false;

				for (x=vBannedIPs.size()-1;x>=0;x--){
					if (vBannedIPs[x].first.compare(sNewConnectionIP) != 0) {continue;}
					i = search(vBanLenght,sNewConnectionIP);

					if (actual - vBannedIPs[x].second >= vBanLenght[i].second.first) { /* Ban timed out */			
						/* Remove from connection list */
						if (!vConnections.empty()){
							for (i=vConnections.size()-1;i>=0;i--) { 
								if (vConnections[i].first.compare(vBannedIPs[x].first) == 0){vConnections.erase(vConnections.begin()+i);}
							}
						}

						vBannedIPs.erase(vBannedIPs.begin()+x); /* Remove from banlist */
						continue;
					}
					if (vBannedIPs[x].first.compare(sNewConnectionIP) == 0) {
						StrmSock.close();
						fExit = true;
						break;
					}
				}
				if (fExit) {continue;}
			}

			/* Remove old banlenght entries */
			if (!vBanLenght.empty()) {
				for (x = vBanLenght.size()-1;x>=0;x--) {
					if (vBanLenght[x].second.second < Timer.elapsed()/1000) { /* last ban was for 5 minutes -> remove it*/
						vBanLenght.erase( vBanLenght.begin()+x);
					}
				}
			}

			/* Manage connection list + ban if needed */
			vConnections.push_back(std::make_pair(sNewConnectionIP,Timer.elapsed()/1000L)); /* Add connection to list */
			iCount = 0;
			lowest = 30000;
			fExit = false;
			for (x=vConnections.size()-1;x>=0;x--) {
				if ((Timer.elapsed()/1000) - vConnections[x].second >= 30000){ /* Entry is old, remove it */
					vConnections.erase(vConnections.begin()+x);
					continue;
				}

				/* Timespan between actual time and connection time of this entry */
				actual = (Timer.elapsed()/1000) - vConnections[x].second;

				if (vConnections[x].first.compare(sNewConnectionIP) == 0) { /* This IP connected more than one time */
					iCount++;
					if (actual < lowest) {lowest = actual;}
				}

				/* More than four connections in a timespan of 10 seconds -> ban IP */
				if (iCount > 4 && lowest <= 10000) {
					StrmSock.close();
					vBannedIPs.push_back(std::make_pair(sNewConnectionIP,Timer.elapsed()/1000));

					/* Set banlenght */
					if ((x = search(vBanLenght,sNewConnectionIP)) == -1) {
						vBanLenght.push_back(std::make_pair(sNewConnectionIP,std::make_pair(10000,Timer.elapsed()/1000 + 5*60*1000)));
						/*x = vBanLenght.size()-1;*/
					}else{
						vBanLenght[x].second.first *= 2;
						vBanLenght[x].second.second = Timer.elapsed()/1000 + (5*60*1000) + vBanLenght[x].second.first;
					}
					/*cout<<vBanLenght[x].first<<" banned for:"<< (vBanLenght[x].second.first/1000)<<" seconds\n";*/

					fExit = true;
					break;
				}
			}
			if (fExit) {continue;}
			#endif

			if (!_pMinecraftServer->getPlayerPool()->isAnySlotFree()) { //There is no free slot
				StrmSock.sendBytes(_preparedServerFullMsg.c_str(),_preparedServerFullMsg.length());
				StrmSock.close();
				continue;
			}

			_pMinecraftServer->getPlayerPool()->Assign(StrmSock);
		}catch(...) {       /* Only happen if socket become closed */
			_iThreadStatus = FC_THREADSTATUS_DEAD;
			return;
		}
	}
}