Example #1
0
/**
 * Test that pausing a connection works.
 */
void AdvancedTCPConnectorTest::testPause() {
  ola::network::TCPSocketFactory socket_factory(
      ola::NewCallback(this, &AdvancedTCPConnectorTest::AcceptedConnection));
  TCPAcceptingSocket listening_socket(&socket_factory);
  SetupListeningSocket(&listening_socket);

  AdvancedTCPConnector connector(
      m_ss,
      m_tcp_socket_factory.get(),
      TimeInterval(0, CONNECT_TIMEOUT_IN_MS * 1000));

  // 5 per attempt, up to a max of 30
  LinearBackoffPolicy policy(TimeInterval(5, 0), TimeInterval(30, 0));
  // add endpoint, but make sure it's paused
  connector.AddEndpoint(m_server_address, &policy, true);
  OLA_ASSERT_EQ(1u, connector.EndpointCount());

  ConfirmState(__LINE__, connector, m_server_address,
               AdvancedTCPConnector::PAUSED, 0);

  m_ss->RunOnce(TimeInterval(0, 500000));

  // now unpause
  connector.Resume(m_server_address);
  // The socket may be connected immediately depending on the platform.
  AdvancedTCPConnector::ConnectionState state;
  unsigned int failed_attempts;
  connector.GetEndpointState(m_server_address, &state, &failed_attempts);
  if (state == AdvancedTCPConnector::DISCONNECTED) {
    m_ss->Run();
  }
  OLA_ASSERT_EQ(1u, connector.EndpointCount());
  ConfirmState(__LINE__, connector, m_server_address,
               AdvancedTCPConnector::CONNECTED, 0);

  // check our socket exists
  OLA_ASSERT_TRUE(m_connected_socket);
  m_connected_socket->Close();
  delete m_connected_socket;
  connector.Disconnect(m_server_address, true);

  // state should be updated
  ConfirmState(__LINE__, connector, m_server_address,
               AdvancedTCPConnector::PAUSED, 0);

  // clean up
  connector.RemoveEndpoint(m_server_address);
  OLA_ASSERT_EQ(0u, connector.EndpointCount());

  m_ss->RemoveReadDescriptor(&listening_socket);
}
Example #2
0
int main(int argc, char * *argv)
{
	console = new Console();

	/* Begin your application here. */
	int cc_err;

	TCPSocket * sock = new TCPSocket();
	console->WriteLine("Connecting...");
	cc_err = sock->Connect("www.example.com", 80);
	if (cc_err == CC_ERR_WOULD_BLOCK)
		console->WriteLine("Non-blocking sockets are enabled. Waiting for connection...");
	while (sock->State() == SOCKET_STATE_CONNECTING) ;
	if (sock->State() != SOCKET_STATE_CONNECTED) {
		console->WriteLine("Connection failed.");
		return 1;
	} else
		console->WriteLine("Connection seems OK.");
	console->Write("Requesting http://www.example.com/... ");
	cc_err = sock->Send("GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n");
	if (cc_err < 1)
		console->WriteLine("Failed.");
	else
		console->WriteLine("OK");

	while (sock->State() == SOCKET_STATE_CONNECTED) {
		string in;
		cc_err = sock->Read(in);
		if (cc_err == 0) {
			console->WriteLine(in);
			break;
		} else {
			if (cc_err != CC_ERR_WOULD_BLOCK)
				console->WriteLine("Read error %d (%s)", cc_err, GetErrorDescription(cc_err));
			System::ThreadSleep(10);
		}
	}

	sock->Close();

	delete sock;

	/* End your application here. */

#ifdef TARGET_OS_WINDOWS
	system("pause");
#endif

	delete console;
	return 0;
}
Example #3
0
//---------------------------------------
bool TCPAcceptSocket::Accept(TCPSocket& po_rxConnection)
{
	if(!IsOpen()) return false;
	po_rxConnection.Close();
	WSAResetEvent(m_hEvent);

	sockaddr xA;
	int iSize=sizeof(xA);
	po_rxConnection.m_xSock=WSAAccept(m_xSock,&xA,&iSize,NULL,0);
	if((po_rxConnection.m_xSock==INVALID_SOCKET)||(po_rxConnection.m_xSock==WSAEWOULDBLOCK))
		return false;
	po_rxConnection.m_hClose=WSACreateEvent();
	WSAEventSelect(po_rxConnection.m_xSock,po_rxConnection.m_hClose,FD_CLOSE);
	return true;
}
/*
 * Test that a TCP Connect works.
 */
void AdvancedTCPConnectorTest::testConnect() {
  ola::network::TCPSocketFactory socket_factory(
      ola::NewCallback(this, &AdvancedTCPConnectorTest::AcceptedConnection));
  TCPAcceptingSocket listening_socket(&socket_factory);
  SetupListeningSocket(&listening_socket);

  AdvancedTCPConnector connector(
      m_ss,
      m_tcp_socket_factory.get(),
      TimeInterval(0, CONNECT_TIMEOUT_IN_MS * 1000));

  // 5 per attempt, up to a max of 30
  LinearBackoffPolicy policy(TimeInterval(5, 0), TimeInterval(30, 0));
  connector.AddEndpoint(m_server_address, &policy);
  OLA_ASSERT_EQ(1u, connector.EndpointCount());

  m_ss->Run();
  OLA_ASSERT_EQ(1u, connector.EndpointCount());

  // confirm the status is correct
  ConfirmState(__LINE__, connector, m_server_address,
               AdvancedTCPConnector::CONNECTED, 0);

  // check our socket exists
  OLA_ASSERT_TRUE(m_connected_socket);
  m_connected_socket->Close();
  delete m_connected_socket;
  OLA_INFO << "disconnecting";
  connector.Disconnect(m_server_address, true);

  // state should be updated
  ConfirmState(__LINE__, connector, m_server_address,
               AdvancedTCPConnector::PAUSED, 0);

  // remove & shutdown
  connector.RemoveEndpoint(m_server_address);
  OLA_ASSERT_EQ(0u, connector.EndpointCount());
  m_ss->RemoveReadDescriptor(&listening_socket);
}
Example #5
0
void TCPConnection::BaseCommand(Params &request, ProcessDone_cb callback)
{
    Params result = request;
    if (request["0"] == "version")
    {
        cDebugDom("network") << "version";
        if (request["1"] == "?")
            result.Add("1", Utils::get_config_option("fw_version"));
    }
    else if (request["0"] == "save")
    {
        cDebugDom("network") << "save";

        Config::Instance().SaveConfigIO();
        Config::Instance().SaveConfigRule();

        if (request["1"] == "default")
        {
            //copy the default config files
            Utils::file_copy(ETC_DIR"io.xml", "/mnt/ext3/calaos/io.default");
            Utils::file_copy(ETC_DIR"rules.xml", "/mnt/ext3/calaos/rules.default");
        }
    }
    else if (request["0"] == "system")
    {
        cDebugDom("network") << "system";

        if (request["1"] == "reboot")
        {
            if (request["2"] == "calaos_gui")
            {
                int unused = system("killall -9 calaos_gui");
                unused = system("killall -9 calaos_thumb");
                (void)unused;
            }
            else if (request["2"] == "calaosd")
            {
                int unused = system("killall -9 calaosd");
                (void)unused;
            }
            else if (request["2"] == "all")
            {
                int unused = system("reboot");
                (void)unused;
            }
        }
        else if(request["1"] == "date")
        {
            vector<string> vcmd;
            for(int i=0;i<request.size();i++)
            {
                string s = Utils::to_string(i);
                vcmd.push_back(request[s]);

            }
            NTPClock::Instance().setNetworkCmdCalendarApply(vcmd);
            NTPClock::Instance().setRestartWhenApply(false);
            IPC::Instance().SendEvent("CalaosCommon::NTPClock","applyCalendar",NULL);

            result.Add("2", "ok");

            string cmd = "";
            for(int i=0;i<9;i++)
                cmd+=request[Utils::to_string(i)]+" ";
            //envoie de la commandes aux clients
            TCPSocket *sock;
            sock = new TCPSocket;
            sock->Create(UDP);
            sock->Broadcast(cmd, BCAST_UDP_PORT);
            sock->Close();
            delete sock;
        }
    }
    else if (request["0"] == "firmware")
    {
        cDebugDom("network") << "firmware";

        if (request["1"] == "webupdate")
        {
            //try to update firmware from /tmp/image.tar.bz2
            cDebugDom("network") << "save: Firmware update requested by web.";
            int unused = system("fw_update.sh");
            (void)unused;
        }
    }
    else if (request["0"] == "poll_listen")
    {
        cDebugDom("network") << "poll_listen";

        if (request["1"] == "register")
        {
            string uuid = PollListenner::Instance().Register();
            result.Add("2", uuid);
        }
        else if (request["1"] == "unregister")
        {
            if (PollListenner::Instance().Unregister(request["2"]))
                result.Add("2", "true");
            else
                result.Add("2", "false");
        }
        else if (request["1"] == "get")
        {
            Params events;

            bool res = PollListenner::Instance().GetEvents(request["2"], events);

            result.Add("2", "");

            if (!res)
            {
                result.Add("2", "error");
            }
            else
            {
                int c = 2;

                for (int i = 0;i < events.size();i++)
                {
                    string key, value;
                    events.get_item(i, key, value);

                    result.Add(Utils::to_string(c), key + ":" + url_encode(value));

                    c++;
                }
            }
        }
    }

    ProcessDone_signal sig;
    sig.connect(callback);
    sig.emit(result);
}
Example #6
0
int main( int argc, char *argv[] )
{
#ifdef TEST_TCP_SOCKETS

  StartWinSock();

  TCPSocket listener;
  TCPSocket client;

  char *localIP = NULL;
  GetLocalIP( localIP );

  listener.SetIP( localIP );
  listener.SetPortNumber( 8000 );

  listener.Init();
  
  listener.Listen();

  while( !listener.Accept( client ) );
  
  while( true )
  {
    std::string message;
    Prompt( message, "Enter a message" );

    NetworkMessage netMessage;
    netMessage.msg_.Assign( message.c_str(), message.size() );

    client.Send( netMessage );
  }

  client.Shutdown();
  client.Close();

  listener.Shutdown();
  listener.Close();

  CloseWinSock();

#endif

  /*
  GameControl controller;

  try
  {
    controller.Init();

    try
    {
      controller.Run();
    }
    catch( BaseErrExcep e )
    {
      e.Print();
    }

    controller.Close();
  }
  catch( BaseErrExcep e )
  {
    e.Print();
  }
  */

    FileServer fileServer;

    try
    {
        fileServer.Init();

        try
        {
            fileServer.Run();
        }
        catch(BaseErrExcep& e)
        {
            e.Print();
        }

        fileServer.Close();
    }
    catch(BaseErrExcep& e)
    {
        e.Print();
    }
 
   
  printf( "\n Server is closing \n" );

  return WaitForInput();
}