예제 #1
0
void RemoteUDPListener::run()
{
	poco_assert (_stopped);

	Poco::Buffer<char> buffer(BUFFER_SIZE);
	_stopped = false;
	Poco::Timespan waitTime(WAITTIME_MILLISEC* 1000);
	while (!_stopped)
	{
		try
		{
			if (_socket.poll(waitTime, Socket::SELECT_READ))
			{
				int byteCnt = _socket.receiveBytes(buffer.begin(), BUFFER_SIZE);
				if (byteCnt > 0)
				{
					_queue.enqueueNotification(new MessageNotification(std::string(buffer.begin(), byteCnt)));
				}
			}
		}
		catch (...)
		{
			// lazy exception catching
		}
	}
}
예제 #2
0
	void SSDPMsearchSender::unicast(const string & content, InetAddress & remoteAddr) {
		DatagramSocket sock;
		char * buffer = new char[content.size()];
		DatagramPacket packet(buffer, content.size(), remoteAddr);
		packet.write(content);
		sock.send(packet);
		delete[] buffer;
	}
예제 #3
0
	virtual void test() {
		DatagramSocket socket;
		char data[1024] = {0,};
		DatagramPacket packet(data, sizeof(data), "127.0.0.1", 8080);
		packet.write("hello");
		packet.write(" world");
		socket.send(packet);
		socket.close();
	}
예제 #4
0
TEST(DatagramSocket, testEcho)
{
    DatagramSocket ss;
    ss.connect(SocketAddress("www.opendns.com", 53));
    int n = ss.sendBytes(dns_query, sizeof(dns_query));
    //EXPECT_TRUE (n == sizeof(dns_query));
    //char buffer[256];
    //n = ss.receiveBytes(buffer, sizeof(buffer));
    //EXPECT_TRUE (n == 5);
    //EXPECT_TRUE (std::string(buffer, n) == "hello");
    ss.close();
}
예제 #5
0
void DatagramSocketTest::testUnbound()
{
	UDPEchoServer echoServer;
	DatagramSocket ss;
	char buffer[256];
	ss.connect(SocketAddress("localhost", echoServer.port()));
	int n = ss.sendBytes("hello", 5);
	assert (n == 5);
	n = ss.receiveBytes(buffer, sizeof(buffer));
	assert (n == 5);
	assert (std::string(buffer, n) == "hello");
	ss.close();
}
예제 #6
0
void DatagramSocketTest::testSendToReceiveFrom()
{
	UDPEchoServer echoServer(SocketAddress("localhost", 0));
	DatagramSocket ss;
	int n = ss.sendTo("hello", 5, SocketAddress("localhost", echoServer.port()));
	assert (n == 5);
	char buffer[256];
	SocketAddress sa;
	n = ss.receiveFrom(buffer, sizeof(buffer), sa);
	assert (sa.host() == echoServer.address().host());
	assert (sa.port() == echoServer.port());
	assert (n == 5);
	assert (std::string(buffer, n) == "hello");
	ss.close();
}
예제 #7
0
파일: SocketTest.cpp 프로젝트: 311labs/SRL
bool SocketTest::udpSocketTest()
{
    DatagramSocket server(TCP_TEST_PORT);
    DatagramSocket client;
    
    InetSocketAddress toaddr(TCP_TEST_PORT);
    client.sendTo(toaddr, TEST_MESSAGE1);
    InetSocketAddress fromaddr;
    char buf[256];
    int len = server.recvFrom(fromaddr, (SRL::byte*)buf, 255);
    buf[len] = '\0';
    String msg = buf;
    TEST_ASSERT(msg == TEST_MESSAGE1)
    server.close();
    return true;
}
예제 #8
0
TEST_F(DatagramSocketTest, SendReceive)
{
    DatagramSocket socket;
    EXPECT_TRUE(socket.Create(AF_INET));
    std::string sent = "12345\n";
    std::string quit = "quit";
    size_t sent_size, received_size;
    char buffer[6];
    size_t buffer_size = 6;
    EXPECT_TRUE(socket.SendTo(sent.data(), sent.size(),
                              m_address, &sent_size));
    EXPECT_EQ(sent.size(), sent_size);
    EXPECT_TRUE(socket.ReceiveFrom(buffer, buffer_size,
                                   &received_size, &m_address));
    EXPECT_EQ(sent.size(), received_size);
    EXPECT_STREQ(sent.data(), buffer);
    EXPECT_TRUE(socket.SendTo(quit.data(), quit.size(),
                              m_address, &sent_size));
}
예제 #9
0
int run_udp_client(InetSocketAddress &addr)
{
    try
    {
        InetSocketAddress from;
        SRL::byte buf[256];
        DateTime dt;
        DatagramSocket client;
        while (1)
        {
            dt.update();
            client.sendTo(addr, dt.asString());
            Console::formatLine("sent: '%s'", dt.asString().text());
            System::Sleep(1000);
        }
        client.close();
    }
    catch (SRL::Errors::Exception &e)
    {
        Console::writeLine(e.message());
    }
    return 0;
}
예제 #10
0
void *serviceMainLoop(void *arg)
{
	char msg[RECV_BUFFSIZE];
	DatagramSocket *datagramSock = new DatagramSocket(BROADCAST_ADDR, BROADCAST_PORT);
	DatagramPrivatePacket *datagreampacket = new DatagramPrivatePacket();
	string recvFrom;
	unsigned int port;

	while(datagramSock)
	{
		if(datagramSock->recevie(recvFrom, port, msg, RECV_BUFFSIZE) > 0)
		{
			if(datagreampacket)
			{
				datagreampacket->parse(msg);
				datagramCommandProcess(datagramSock, recvFrom, port, datagreampacket->getCommandNo());
			}
		}

//		usleep(1000*1000); //1s   Don't sleep because datagram recevie is blocked
	}

	if(datagramSock)
	{
		delete(datagramSock);
		datagramSock = NULL;
	}

	if(datagreampacket)
	{
		delete(datagreampacket);
		datagreampacket = NULL;
	}

	return NULL;
}
예제 #11
0
파일: main.cpp 프로젝트: bjtj/oslayer
	virtual void run() {
		Selector selector;
		socket = new DatagramSocket(1900);
		socket->setReuseAddr();
		socket->setBroadcast();
		socket->joinGroup("239.255.255.250");

		socket->registerSelector(selector);

		while (!interrupted()) {
			if (selector.select(1000) > 0) {
				char buffer[1024] = {0,};
				int len = socket->recv(buffer, sizeof(buffer));
				if (len > 0) {
					buffer[len - 1] = 0;
					cout << "[RECV] >> " << buffer << endl;
				}
			} else {
				idle(10);
			}
		}

		socket->close();
	}
예제 #12
0
int DeviceDiscoverer::discover(
   DeviceList& devices, const char* searchTarget, uint32_t timeout, int count)
{
   int rval = -1;

   // prepare device list
   devices->setType(Array);
   devices->clear();

   // create SSDP request
   HttpRequestHeader requestHeader;
   createRequest(searchTarget, &requestHeader);

   // create socket for sending request
   DatagramSocket socket;

   // bind to any available port
   InternetAddressRef localAddr = new InternetAddress("0.0.0.0", 0);
   if(socket.bind(&(*localAddr)))
   {
      // create the group address
      InternetAddressRef groupAddr = new InternetAddress(
         SSDP_MULTICAST_ADDRESS, SSDP_MULTICAST_PORT);

      // create and send discover request datagram
      DatagramRef request = new Datagram(groupAddr);
      request->assignString(requestHeader.toString().c_str());
      MO_CAT_DEBUG(MO_UPNP_CAT, "Sending UPnP request:\n%s",
         requestHeader.toString().c_str());
      if(socket.send(request))
      {
         // no devices yet
         rval = 0;

         // use timer to comply with user-supplied timeout
         Timer timer;
         timer.start();
         uint32_t remaining = timeout;
         InternetAddressRef addr = new InternetAddress();
         while(rval >= 0 && remaining > 0 && (count == 0 || rval < count))
         {
            // set receive timeout and try to get ssdp responses
            socket.setReceiveTimeout(remaining);

            DatagramRef response = new Datagram(addr);
            response->getBuffer()->resize(2048);
            if(!socket.receive(response))
            {
               // check last exception
               ExceptionRef e = Exception::get();
               if(e->isType("monarch.net.SocketTimeout"))
               {
                  MO_CAT_DEBUG(MO_UPNP_CAT, "UPnP request timed out.");

                  // exception indicates timed out
                  remaining = 0;
               }
               else
               {
                  MO_CAT_ERROR(MO_UPNP_CAT,
                     "UPnP request error: %s",
                     JsonWriter::writeToString(
                        Exception::getAsDynamicObject()).c_str());

                  // some error other than a timeout
                  rval = -1;
               }
            }
            else
            {
               // parse ssdp response
               MO_CAT_DEBUG(MO_UPNP_CAT, "Received UPnP response:\n%s",
                  response->getString().c_str());
               Device device = parseDevice(response->getString().c_str());
               if(device.isNull())
               {
                  MO_CAT_ERROR(MO_UPNP_CAT,
                     "UPnP response parse error: %s",
                     JsonWriter::writeToString(
                        Exception::getAsDynamicObject()).c_str());

                  // error in parsing
                  rval = -1;
               }
               else
               {
                  MO_CAT_DEBUG(MO_UPNP_CAT,
                     "Found UPnP device: %s",
                     JsonWriter::writeToString(device).c_str());

                  // another device found
                  ++rval;
                  devices->append(device);

                  // update remaining time (must be within 32-bit integer range)
                  remaining = (uint32_t)timer.getRemainingMilliseconds(timeout);
               }
            }
         }
      }
   }

   return rval;
}
void DatagramLocalSocketTest::testDatagramSocketPerformance()
{
	Timestamp::TimeDiff local, net;
	std::size_t initBufSize = 1;
	std::size_t initReps = 1;
	double locData = 0.0, locTime = 0.0, netData = 0.0, netTime = 0.0;

	std::cout << std::endl << "OS Name:         " << Environment::osName() << std::endl;
	std::cout << "OS Version:      " << Environment::osVersion() << std::endl;
	std::cout << "OS Architecture: " << Environment::osArchitecture() << std::endl;

	std::ostringstream os;
	os << Environment::osName() << '-' 
		<< Environment::osVersion() << '-' 
		<< Environment::osArchitecture()
		<< "-UDP.csv";
	File f(os.str());
	if (f.exists()) f.remove();
	FileOutputStream fos(os.str());

	for (std::size_t repetitions = initReps;
			repetitions <= 100000;
			repetitions *= 10)
	{
		for (std::size_t bufSize = initBufSize; bufSize < 20000; bufSize *= 2)
		{
			char* pBuf = new char[bufSize];
			{
				UDPLocalEchoServer echoServer(bufSize);
				DatagramSocket ss(SocketAddress("/tmp/poco.client.udp.sock"), true);
				
				SocketAddress addr(echoServer.address().toString());
				ss.connect(addr);
				int recv = 0, sent = 0;
				Stopwatch sw; int i = 0;
				for (; i < repetitions; ++i)
				{
					sent = 0; recv = 0; local = 0;

					do
					{
						int s;
						sw.restart();
						s = ss.sendBytes(pBuf + sent, bufSize - sent);
						sw.stop();
						local += sw.elapsed();
						sent += s;
					} while (sent < bufSize);

					do
					{
						int r;
						sw.restart();
						r = ss.receiveBytes(pBuf + recv, bufSize - recv);
						sw.stop();
						local += sw.elapsed();
						recv += r;
					} while (recv < bufSize);

					locData += sent;
					locData += recv;
					locTime += local;

					poco_assert (sent == bufSize && recv == bufSize);
				}

				std::cout << "Local UDP socket, " << i << " repetitions, " << bufSize << " bytes, " 
					<< local << " [us]." << std::endl;
				ss.close();
			}

			{
				UDPEchoServer echoServer(bufSize);
				DatagramSocket ss;
				ss.connect(SocketAddress("localhost", echoServer.port()));
				int recv = 0, sent = 0;
				Stopwatch sw; int i = 0; 
				for (; i < repetitions; ++i)
				{
					sent = 0; recv = 0; net = 0;

					do
					{
						int s;
						sw.restart();
						s = ss.sendBytes(pBuf + sent, bufSize - sent);
						sw.stop();
						net += sw.elapsed();
						sent += s;
					} while (sent < bufSize);

					do
					{
						int r;
						sw.restart();
						r = ss.receiveBytes(pBuf + recv, bufSize - recv);
						sw.stop();
						net += sw.elapsed();
						recv += r;
					} while (recv < bufSize);

					netData += sent;
					netData += recv;
					netTime += net;

					poco_assert (sent == bufSize && recv == bufSize);
				}
				
				std::cout << "Network UDP socket, " << i << " repetitions, " << bufSize << " bytes, " 
					<< net << " [us]." << std::endl;
				fos << i << ',' << bufSize << ',';
				ss.close();
			}
			delete pBuf;

			double ratio = local ? ((double) net) / ((double) local) : (double) net;
			double diff = ((double) net) - ((double) local);
			std::cout << "Ratio: " << ratio << "(" << diff / 1000.0 << "[us/msg]" << ')' << std::endl;

			fos << ratio << std::endl;
		}
	}

	poco_assert (locData == netData);

	double locDTR = ((locData / (locTime / Timestamp::resolution())) * 8) / 1000000;
	double netDTR = ((netData / (netTime / Timestamp::resolution())) * 8) / 1000000;

	std::cout << "=================================" << std::endl
		<< "Local DTR: " << locDTR << " [Mbit/s]" << std::endl
		<< "Network DTR: " << netDTR << " [Mbit/s]" << std::endl
		<< "Local sockets speedup: " << ((locDTR / netDTR) * 100) - 100 << '%' << std::endl
		<< "=================================" << std::endl;

	fos << "=================================" << std::endl
		<< "Local DTR: " << locDTR << " [Mbit/s]" << std::endl
		<< "Network DTR: " << netDTR << " [Mbit/s]" << std::endl
		<< "Local sockets speedup: " << ((locDTR / netDTR) * 100) - 100 << '%' << std::endl
		<< "=================================" << std::endl;

	fos.close();
}