Exemplo n.º 1
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 LocalPortForwarder::forward(Poco::Net::StreamSocket& socket)
{
	if (_logger.debug())
	{
		_logger.debug(Poco::format("Local connection accepted, creating forwarding connection to %s, remote port %hu", _remoteURI.toString(), _remotePort));
	}
	try
	{
		std::string path(_remoteURI.getPathEtc());
		if (path.empty()) path = "/";
		Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, path, Poco::Net::HTTPRequest::HTTP_1_1);
		request.set(SEC_WEBSOCKET_PROTOCOL, WEBTUNNEL_PROTOCOL);
		request.set(X_WEBTUNNEL_REMOTEPORT, Poco::NumberFormatter::format(_remotePort));
		Poco::Net::HTTPResponse response;
		Poco::SharedPtr<Poco::Net::WebSocket> pWebSocket = _pWebSocketFactory->createWebSocket(_remoteURI, request, response);
		if (response.get(SEC_WEBSOCKET_PROTOCOL, "") != WEBTUNNEL_PROTOCOL)
		{
			_logger.error("The remote host does not support the WebTunnel protocol.");
			pWebSocket->shutdown(Poco::Net::WebSocket::WS_PROTOCOL_ERROR);
			pWebSocket->close();
			socket.close();
			return;
		}

		socket.setNoDelay(true);
		pWebSocket->setNoDelay(true);

		_pDispatcher->addSocket(socket, new StreamSocketToWebSocketForwarder(_pDispatcher, pWebSocket), _localTimeout);
		_pDispatcher->addSocket(*pWebSocket, new WebSocketToStreamSocketForwarder(_pDispatcher, socket), _remoteTimeout);
	}
	catch (Poco::Exception& exc)
	{
		_logger.error(Poco::format("Failed to open forwarding connection: %s", exc.displayText()));
		socket.close();
	}
}
Exemplo n.º 3
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);
    }
}
Exemplo n.º 4
0
	/*! Set the tcp_cork flag
	    \param way boolean true (on) or false(clear) */
	void set_tcp_cork_flag(bool way) const
	{
#if defined HAVE_DECL_TCP_CORK && TCP_CORK != 0
		_sock->setOption(IPPROTO_TCP, TCP_CORK, way ? 1 : 0);
#endif
	}
Exemplo n.º 5
0
	/*! Get the peer socket address
	    \return peer socket address reference */
	Poco::Net::SocketAddress get_peer_socket_address() const { return _sock->peerAddress(); }
	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();
	}
Exemplo n.º 7
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;
}

}
Exemplo n.º 8
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;
		}
	}
}
Exemplo n.º 9
0
/// connect to an event mode control progam and read live events
int liveData(const std::string& host)
{
	static char* junk_buffer[10000];
	Poco::Net::StreamSocket s;
    Poco::UInt16 port = 10000;
	Poco::Net::SocketAddress address(host, port);
	s.connect(address);
	TCPStreamEventDataSetup setup;
    while( s.available() < static_cast<int>(sizeof(setup)) )
	{
		Poco::Thread::sleep(1000);
	}
	s.receiveBytes(&setup, sizeof(setup));
	if ( !setup.isValid() )
	{
		throw std::runtime_error("version wrong");
	}
	std::cerr << "run number " << setup.head_setup.run_number << std::endl; 
	TCPStreamEventDataNeutron events;
	while(true)
	{
        while(s.available() < static_cast<int>(sizeof(events.head)))
		{
			Poco::Thread::sleep(100);
		}
		s.receiveBytes(&events.head, sizeof(events.head));
		if ( !events.head.isValid() )
		{
			throw std::runtime_error("corrupt stream - you should reconnect");
		}
		if ( !(events.head.type == TCPStreamEventHeader::Neutron) )
		{
			throw std::runtime_error("corrupt stream - you should reconnect");
		}
        s.receiveBytes(junk_buffer, events.head.length - static_cast<uint32_t>(sizeof(events.head)));
        while(s.available() < static_cast<int>(sizeof(events.head_n)))
		{
			Poco::Thread::sleep(100);
		}
		s.receiveBytes(&events.head_n, sizeof(events.head_n));
		if ( !events.head_n.isValid() )
		{
			throw std::runtime_error("corrupt stream - you should reconnect");
		}
        s.receiveBytes(junk_buffer, events.head_n.length - static_cast<uint32_t>(sizeof(events.head_n)));
        events.data.resize(events.head_n.nevents);
        uint32_t nread = 0;
		while( nread < events.head_n.nevents )
		{
      uint32_t ntoread = static_cast<uint32_t>(s.available() / static_cast<int>(sizeof(TCPStreamEventNeutron)));
			if ( ntoread > (events.head_n.nevents - nread) )
			{
				ntoread = events.head_n.nevents - nread;
			}
			if (ntoread > 0)
			{
                s.receiveBytes(&(events.data[nread]), ntoread * static_cast<int>(sizeof(TCPStreamEventNeutron)));
				nread += ntoread;
			}
			else
			{
				Poco::Thread::sleep(100);
			}
		}
		if (!events.isValid())
		{
			throw std::runtime_error("corrupt stream - you should reconnect");
		}
        //TCPStreamEventHeader& head = events.head;
		TCPStreamEventHeaderNeutron& head_n = events.head_n;
		std::cerr << "Read " << nread << " events for frame number " << head_n.frame_number << " time " << head_n.frame_time_zero << std::endl;
		for(int i=0; i<10; ++i)
		{
			std::cerr << events.data[i].time_of_flight << " " << events.data[i].spectrum << std::endl;
		}
	}
	s.close();
	return 0;
}