bool readable(SocketDispatcher& dispatcher, Poco::Net::StreamSocket& socket)
	{
		int n = 0;
		try
		{
			n = socket.receiveBytes(_buffer.begin(), static_cast<int>(_buffer.size()));
		}
		catch (Poco::Exception& exc)
		{
			_logger.error("Exception while receiving data: " + exc.displayText());
			shutdown(*_pWebSocket, Poco::Net::WebSocket::WS_UNEXPECTED_CONDITION, _logger);
			cleanupDispatcher(socket, *_pWebSocket);
			return false;
		}
		if (n > 0)
		{
			try
			{
				_pWebSocket->sendFrame(_buffer.begin(), n, Poco::Net::WebSocket::FRAME_BINARY);
				return true;
			}
			catch (Poco::Exception& exc)
			{
				_logger.error("Exception while sending data: " + exc.displayText());
				cleanupDispatcher(socket, *_pWebSocket);
			}
		}
		else
		{
			_logger.debug("Closing connection");
			shutdown(*_pWebSocket, Poco::Net::WebSocket::WS_NORMAL_CLOSE, _logger);
			cleanupDispatcher(socket, *_pWebSocket);
		}
		return false;
	}
// ---
void IntSocketHandler::onReadable (Poco::Net::ReadableNotification* pNf)
{
	pNf -> release(); 
	int n = _socket.receiveBytes (_pBuffer, BUFFER_SIZE);
	if (n > 0)
	{
		// Get the information needed to process the message.
		// This information is hiden in the reactor object.
		// The informastion needed is the log system,
		// the message builder, and the notification queue..
		VSWIntSocketReactor* mReactor = 
			dynamic_cast <VSWIntSocketReactor*> (&this -> _reactor);
		CMTYLogSystemPt lSys = mReactor -> logSystem ();
		VSWRemoteServerDataCntReaderImpl* cRemote = mReactor -> remote ();

		// Copy the message readen into an string
		// to simplify further processes...
		char* toProcess = new char [n + 1];
		memcpy (toProcess, _pBuffer, n);
		toProcess [n] = 0; // Must be an string...
		std::string toProcessStr (toProcess);
		delete toProcess;

		// Log the message...
		lSys -> storeText (toProcessStr); 

		// Store the received message into the remote data content reader
		cRemote -> setDataFromMessage (toProcessStr);
	}
	else
		delete this; 
		// Something wrong has been readed...
}
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;
}
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;
}
Beispiel #5
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);
    }
}
Beispiel #6
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;
}

}
Beispiel #7
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;
}