/* * Test non-blocking TCP connects work correctly. */ void TCPConnectorTest::testNonBlockingConnect() { ola::network::TCPSocketFactory socket_factory( ola::NewCallback(this, &TCPConnectorTest::AcceptedConnection)); TCPAcceptingSocket listening_socket(&socket_factory); IPV4SocketAddress listen_address(m_localhost, 0); OLA_ASSERT_TRUE_MSG(listening_socket.Listen(listen_address), "Failed to listen"); GenericSocketAddress addr = listening_socket.GetLocalAddress(); OLA_ASSERT_TRUE(addr.IsValid()); // calling listen a second time should fail OLA_ASSERT_FALSE(listening_socket.Listen(listen_address)); OLA_ASSERT_TRUE(m_ss->AddReadDescriptor(&listening_socket)); // now attempt a non-blocking connect // because we're connecting to the localhost this may run this callback // immediately. TCPConnector connector(m_ss); TimeInterval connect_timeout(0, CONNECT_TIMEOUT_IN_MS * 1000); TCPConnector::TCPConnectionID id = connector.Connect( addr.V4Addr(), connect_timeout, ola::NewSingleCallback(this, &TCPConnectorTest::OnConnect)); OLA_ASSERT_TRUE(id); m_ss->Run(); OLA_ASSERT_EQ(0u, connector.ConnectionsPending()); m_ss->RemoveReadDescriptor(&listening_socket); }
/** * For certain tests we need to ensure there isn't something listening on a TCP * port. The best way I've come up with doing this is to bind to port 0, then * close the socket. REUSE_ADDR means that the port shouldn't be allocated * again for a while. */ uint16_t AdvancedTCPConnectorTest::ReservePort() { TCPAcceptingSocket listening_socket(NULL); IPV4SocketAddress listen_address(m_localhost, 0); OLA_ASSERT_TRUE_MSG(listening_socket.Listen(listen_address), "Failed to listen"); GenericSocketAddress addr = listening_socket.GetLocalAddress(); OLA_ASSERT_TRUE(addr.IsValid()); return addr.V4Addr().Port(); }
/* * Called when a connection completes or times out. */ void AdvancedTCPConnectorTest::OnConnect(TCPSocket *socket) { OLA_ASSERT_NOT_NULL(socket); GenericSocketAddress address = socket->GetPeerAddress(); OLA_ASSERT_TRUE(address.Family() == AF_INET); OLA_ASSERT_EQ(m_localhost, address.V4Addr().Host()); m_connected_socket = socket; m_ss->Terminate(); }
/** * Setup a TCP socket that accepts connections */ void AdvancedTCPConnectorTest::SetupListeningSocket( TCPAcceptingSocket *listening_socket) { IPV4SocketAddress listen_address(m_localhost, 0); OLA_ASSERT_TRUE_MSG(listening_socket->Listen(listen_address), "Failed to listen"); // calling listen a second time should fail OLA_ASSERT_FALSE(listening_socket->Listen(listen_address)); GenericSocketAddress addr = listening_socket->GetLocalAddress(); OLA_ASSERT_TRUE(addr.IsValid()); m_server_address = addr.V4Addr(); OLA_INFO << "listening on " << m_server_address; OLA_ASSERT_TRUE(m_ss->AddReadDescriptor(listening_socket)); }