Ejemplo n.º 1
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);
    }
}
Ejemplo n.º 2
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;
}

}