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; }
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(); }
/** 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; } }
/// 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; }