Пример #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);
    }
}
	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();
	}