int Master::Main(int iArgc, char **ppArgv)
{
    if(3 != iArgc)
    {
        cout<<endl<<"Usage:: master <IP> <Port>";
        return 0;
    }
    
    int iErr;
    
    unsigned int uAddr    = atoi(ppArgv[1]);
    unsigned short usPort = htons(atoi(ppArgv[2]));
    short sFamily         = AF_INET;
    SockAddr serverAddr(uAddr , usPort, sFamily);

    RegisterSigHandler(SIGUSER1, Master::SignalHandler);
	RegisterSigHandler(SIGINTR,  Master::SignalHandler);
    ListenerHandler *pListener = ListenerService::Create<SockAddr &>(serverAddr);
    assert(NULL != pListener);
    RecvHandler *pReceiver = RecvService::Create<MsgBuffer *>(&messageBox);
    assert(NULL != pReceiver);
    pListener->Init();
    pReceiver->Init();
    //SpawnProcess("node1", ppArgv);
    TRACE(this, "Master State", "IDLE");
    InternalWait();
	TRACE(this, "Master State", "DOWN");
    return 0;
}
Exemple #2
0
Pothos::ProxyEnvironment::Sptr EnvironmentEval::makeEnvironment(void)
{
    if (_zoneName == "gui") return Pothos::ProxyEnvironment::make("managed");

    const auto hostUri = getHostProcFromConfig(_zoneName, _config).first;

    //connect to the remote host and spawn a server
    auto serverEnv = Pothos::RemoteClient(hostUri).makeEnvironment("managed");
    auto serverHandle = serverEnv->findProxy("Pothos/RemoteServer")("tcp://"+Pothos::Util::getWildcardAddr(), false/*noclose*/);

    //construct the uri for the new server
    auto actualPort = serverHandle.call<std::string>("getActualPort");
    Poco::URI newHostUri(hostUri);
    newHostUri.setPort(std::stoul(actualPort));

    //connect the client environment
    auto client = Pothos::RemoteClient(newHostUri.toString());
    client.holdRef(Pothos::Object(serverHandle));
    auto env = client.makeEnvironment("managed");

    //determine log delivery address
    //FIXME syslog listener doesn't support IPv6, special precautions taken:
    const auto logSource = (not _zoneName.isEmpty())? _zoneName.toStdString() : newHostUri.getHost();
    const auto syslogListenPort = Pothos::System::Logger::startSyslogListener();
    Poco::Net::SocketAddress serverAddr(env->getPeeringAddress(), syslogListenPort);

    //deal with IPv6 addresses because the syslog server only binds to IPv4
    if (serverAddr.family() == Poco::Net::IPAddress::IPv6)
    {
        //convert IPv6 mapped ports to IPv4 format when possible
        if (serverAddr.host().isIPv4Mapped())
        {
            const Poco::Net::IPAddress v4Mapped(static_cast<const char *>(serverAddr.host().addr())+12, 4);
            serverAddr = Poco::Net::SocketAddress(v4Mapped, std::stoi(syslogListenPort));
        }

        //convert an IPv4 loopback address into an IPv4 loopback address
        else if (serverAddr.host().isLoopback())
        {
            serverAddr = Poco::Net::SocketAddress("127.0.0.1", syslogListenPort);
        }

        //otherwise warn because the forwarding will not work
        else
        {
            poco_warning_f1(Poco::Logger::get("PothosGui.EnvironmentEval.make"),
                "Log forwarding not supported over IPv6: %s", logSource);
            return env;
        }
    }

    //setup log delivery from the server process
    env->findProxy("Pothos/System/Logger").callVoid("startSyslogForwarding", serverAddr.toString());
    env->findProxy("Pothos/System/Logger").callVoid("forwardStdIoToLogging", logSource);
    serverHandle.callVoid("startSyslogForwarding", serverAddr.toString(), logSource);

    return env;
}
GResult HttpClient::connect()
{
    if (serverAddr().ipAddr().ipStr().empty())
    {
    	return G_NO;
    }
	
    return G_YES;
}
int UDPGenerator::rescuerHandSake(
    const ACE_TCHAR * remotehost,
    u_short remoteport)
{
    ACE_DEBUG ((LM_DEBUG, "Sender::initiate_write called\n"));
    const size_t max_payload_size = 4 + ACE_CDR::MAX_ALIGNMENT; //pading

    u_short myid = htons(5);
    u_short mysize = htons(0);

    ACE_Message_Block* body = 0;
    ACE_NEW_RETURN(body, ACE_Message_Block(4), -1);
    body->copy((const char *)&myid, 2);
    body->copy((const char *)&mysize, 2);

    size_t number_of_bytes_sent = 0;
    ACE_INET_Addr serverAddr(remoteport, remotehost);
    int res = this->wd_.send(
                  body, number_of_bytes_sent,
                  0,
                  serverAddr,
                  this->act_);

    switch (res)
    {
    case 0:
        // this is a good error.  The proactor will call our handler when the
        // send has completed.
        break;
    case 1:
        // actually sent something, we will handle it in the handler callback
        ACE_DEBUG ((LM_DEBUG, "********************\n"));
        ACE_DEBUG ((LM_DEBUG,
                    "%s = %d\n",
                    "bytes sent immediately",
                    number_of_bytes_sent));
        ACE_DEBUG ((LM_DEBUG, "********************\n"));
        res = 0;
        break;
    case -1:
        // Something else went wrong.
        ACE_ERROR ((LM_ERROR,
                    "%p\n",
                    "ACE_Asynch_Write_Dgram::recv"));
        // the handler will not get called in this case so lets clean up our msg
        body->release ();
        break;
    default:
        // Something undocumented really went wrong.
        ACE_ERROR ((LM_ERROR,
                    "%p\n",
                    "ACE_Asynch_Write_Dgram::recv"));
        body->release ();
        break;
    }
    return res;
}
void Connection::latencyTest()
{
    QHostAddress serverAddr(profile.serverAddress);
    if (serverAddr.isNull()) {
        QHostInfo::lookupHost(profile.serverAddress, this, SLOT(onServerAddressLookedUp(QHostInfo)));
    } else {
        testAddressLatency(serverAddr);
    }
}
Exemple #6
0
void threadFunc(EventLoop* loop)
{
	InetAddress serverAddr("127.0.0.1", 9981);
	TcpClient client(loop, serverAddr, "TcpClient");

	client.connect();

	sleep(1);
	// client destructs when connected.
}
int Node2::Main(int iArgc, char **ppArgv)
{
    int iErr;

    unsigned int uAddr    = atoi(ppArgv[1]);
    unsigned short usPort = htons(atoi(ppArgv[2]));
    short sFamily         = AF_INET;
    
    SockAddr serverAddr(uAddr , usPort, sFamily);
    DispatchHandler *pDispatcher = DispatchService::Create();
    assert(NULL != pDispatcher);

    pDispatcher->Init(); // It is important to call this to start the service

    // Making two connections
    DispatchHandle dHandle1, dHandle2;
    dHandle1(serverAddr);
    dHandle2(serverAddr);

    for(int i = 1; i <= 2000 ;++i)
    {
        char aMessage[64];
        int iLen = snprintf(aMessage, sizeof(aMessage), "Test message %d", i);
        TLV tlv;
        tlv.tl.iType   = 0;
        tlv.tl.uLength = iLen;
        tlv.pcValue    = aMessage;

        unsigned int uMsgLen = 0;
        char *pMsg = NULL;
        (void)MsgOper::Create(pMsg, uMsgLen, tlv);
        if(NULL != pMsg)
        {
            if(0 == (i % 2))
            {
                pDispatcher->Send(pMsg, dHandle1);
            }
            else
            {
                pDispatcher->Send(pMsg, dHandle2);
            }
            //Testing message integrity
            TLV test;
            MsgOper::Get(pMsg, test);
            std::string str(test.pcValue, test.tl.uLength);
            TRACE(this, "Send Message", str);
        }
        else
        {
            TRACE(this, "Create msg", "FAILED");
        }
    }
    sleep(10);
    return 0;
}
Exemple #8
0
int main(int argc, char* argv[])
{
	Logger::setLogLevel(Logger::TRACE);
	EventLoop loop;
	InetAddress serverAddr("127.0.0.1", 9981); // no such server
	TcpClient client(&loop, serverAddr, "TcpClient");
 	client.connect();

	client.setConnectionCallback(connectCallback);
	client.setMessageCallback(messageCallback);
	loop.loop();
}
int main(int argc, char** argv) {
  std::string serverIP = "127.0.0.1";
  int serverPort = 9981;
  if(argc >= 2)
    serverIP = std::string(argv[1]);
  if(argc >= 3)
    serverPort = atoi(argv[2]);
  muduo::net::InetAddress serverAddr(serverIP, serverPort);
  muduo::net::EventLoop loop;
  QueenClient client(&loop, serverAddr);

  loop.loop();

  return 0;
}
void Connection::latencyTest()
{
    QHostAddress serverAddr(profile.serverAddress);
    if (serverAddr.isNull()) {
        //TODO use a non-blocking function
        QList<QHostAddress> results = QHostInfo::fromName(profile.serverAddress).addresses();
        if (!results.isEmpty()) {
            serverAddr = results.first();
        }
    }
    QSS::AddressTester *addrTester = new QSS::AddressTester(serverAddr, profile.serverPort, this);
    connect(addrTester, &QSS::AddressTester::lagTestFinished, this, &Connection::onLagTestFinished);
    connect(addrTester, &QSS::AddressTester::lagTestFinished, addrTester, &QSS::AddressTester::deleteLater);
    addrTester->startLagTest();
}
Exemple #11
0
int BotMonitor::start(void)
{
	if (TcpMonitor::start() != 0)
	{
		return -1;
	}

	InetAddr serverAddr(BOT_DATA->m_strIp, BOT_DATA->m_nPort);
	BOT_MONITOR->connect(serverAddr);

	Buffer *buffer = new Buffer();
	*buffer << 0;

	BOT_MONITOR->allSend(buffer);

	return 0;
}
int main(int argc, char** argv) {
  std::string serverIp = "127.0.0.1";
  int serverPort = 9981;
  int numberThread = 4;
  if(argc >= 3) {
    serverIp = std::string(argv[1]);
    serverPort = atoi(argv[2]);
  }
  if(argc >= 4) 
    numberThread = atoi(argv[3]);

  muduo::net::EventLoop loop;
  muduo::net::InetAddress serverAddr(serverIp, serverPort);
  QueenWorker worker(&loop, serverAddr, numberThread);
  worker.start();
  loop.loop();

  return 0;
}
Exemple #13
0
void StartFlow(ns3::Ptr<ns3::Socket> sock, const char* to, uint16_t port_number)
{
  SgFlow* flow = getFlowFromSocket(sock);
  ns3::InetSocketAddress serverAddr(to, port_number);

  sock->Connect(serverAddr);
  // tell the tcp implementation to call send_cb again
  // if we blocked and new tx buffer space becomes available
  sock->SetSendCallback(MakeCallback(&send_cb));
  // Notice when the send is over
  sock->SetRecvCallback(MakeCallback(&receive_callback));
  // Notice when we actually sent some data (mostly for the TRACING module)
  sock->SetDataSentCallback(MakeCallback(&datasent_cb));

  XBT_DEBUG("startFlow of F[%p, %p, %u] dest=%s port=%d", flow, flow->action_, flow->totalBytes_, to, port_number);

  sock->SetConnectCallback(MakeCallback(&succeededConnect_callback), MakeCallback(&failedConnect_callback));
  sock->SetCloseCallbacks(MakeCallback(&normalClose_callback), MakeCallback(&errorClose_callback));
}
/**
 * UDPGenerator::gloveDgramWrite
 *
 * @param remotehost
 * @param remoteport
 * @param glovedata
 *
 * @return
 */
int UDPGenerator::gloveDgramWrite(
    const ACE_TCHAR * remotehost,
    u_short remoteport,
    const DataGloveData &glovedata)
{
    ACE_DEBUG ((LM_DEBUG, "Sender::initiate_write called\n"));
    const size_t max_payload_size =
        4 //boolean alignment flag
        + 4 //payload length
        + glovedata.length // Data Glove data length
        + ACE_CDR::MAX_ALIGNMENT; //pading

    // Rescuer header
    u_short myid = htons(5);
    u_short mysize = htons(max_payload_size);

    ACE_Message_Block* rescuerheader= 0;
    ACE_NEW_RETURN(rescuerheader, ACE_Message_Block(4), -1);
    rescuerheader->copy((const char *)&myid, 2);
    rescuerheader->copy((const char *)&mysize, 2);

    // My DGS stuff (header and payload)
    ACE_OutputCDR header (ACE_CDR::MAX_ALIGNMENT + 8);
    header << ACE_OutputCDR::from_boolean (ACE_CDR_BYTE_ORDER);
    header << ACE_CDR::ULong(length);

    // DGS Payload
    ACE_OutputCDR payload (max_payload_size);
    payload << glovedata;
    ACE_CDR::ULong length = payload.total_length();

    iovec iov[3];
    iov[0].iov_base = rescuerheader->rd_ptr();
    iov[0].iov_len  = 4;
    iov[1].iov_base = header.begin()->rd_ptr();
    iov[1].iov_len  = HEADER_SIZE;
    iov[2].iov_base = payload.begin()->rd_ptr();
    iov[2].iov_len  = length;

    ACE_INET_Addr serverAddr(remoteport, remotehost);
    return sockDgram_.send(iov,3,  serverAddr );
}
int main()
{
	EventLoop* baseLoop = new EventLoop;;
	InetAddress serverAddr("127.0.0.1", 8888);
	std::shared_ptr<TcpClient> tcpClient(new TcpClient(baseLoop, serverAddr, "test"));
	tcpClient->connect();
	
	std::unique_ptr<Thread> thread(new Thread([=] {
					char buf[64];
					while (true) {
						bzero(buf, sizeof buf);
						char* tmp = buf;
						gets(tmp);
						tcpClient->connection()->send(buf);
					}
				}));
	
	thread->start();
	baseLoop->loop();

	thread->join();
	return 0;
}
	GameController::GameController(GameApplication *app, const Size &viewport, CharacterDataPtr character) :
		DRController(app, viewport, "GameMain.xml"),
		mInstance(nullptr),
		mKeyMap(L"DefaultKeymap.kmp"),
		mPlayer(NULL),
		mReadyState(GameLoading),
		mCharacter(character),
		mDebugRay(NULL),
		mChatClient(NULL)
	{
		float aspect = viewport.width / viewport.height;
		mCamera = new PerspectiveCamera(aspect, 45.0f, 1.0, 1000.0f, viewport);

		mLoadingImage = new View(0, 0, viewport.width, viewport.height);
		mLoadingImage->SetBackgroundImage("molten_chasm_loading.jpg");
		mLoadingImage->SetZPosition(1000);
		this->GetView()->AddSubview(mLoadingImage);

		NetworkAddress serverAddr("192.168.1.8", 7000);
		mNetworkClient = new NetworkClient(serverAddr);
		mNetworkClient->SetListener(this);
		mNetworkClient->CreateInstance(character->GetId());
	}
Exemple #17
0
void CFiberConnect::run(void)
{
#if 0
	acl::string serverAddr(m_serverAddr);
	char *addr = serverAddr.c_str();
	char *port_s = strchr(addr, ':');

	ASSERT(port_s && *(port_s + 1));
	*port_s++ = 0;

	struct sockaddr_in sa;
	int len = sizeof(sa);
	memset(&sa, 0, sizeof(sa));
	sa.sin_family = AF_INET;
	sa.sin_port   = htons(atoi(port_s));
	sa.sin_addr.s_addr = inet_addr(addr);

	socket_t sock = acl_fiber_socket(AF_INET, SOCK_STREAM, 0);

	if (acl_fiber_connect(sock, (const struct sockaddr*) &sa, len) < 0)
		printf("connect %s error %s\r\n", m_serverAddr.c_str(),
			acl::last_serror());
	else
		doEcho(sock);

	acl_fiber_close(m_sock);
#else
	acl::socket_stream conn;
	if (conn.open(m_serverAddr, 10, 0) == false)
		printf("connect %s error %s\r\n", m_serverAddr.c_str(),
			acl::last_serror());
	else
		doEcho(conn);
#endif
	m_hWin.OnFiberConnectExit();
	delete this;
}
Exemple #18
0
int ACE_TMAIN (int argc, ACE_TCHAR **argv){

  Options_Manager optsMgr(argc, argv, ACE_TEXT ("server-opts"));

  // show usage is requested
  if (optsMgr._usage) {
    optsMgr._show_usage(stderr, ACE_TEXT ("server-opts"));
    return 1;
  }

  // If SCTP is not installed then terminate the program, unless TCP
  // was specified.
#ifndef ACE_HAS_SCTP
  if (optsMgr.test_transport_protocol == IPPROTO_SCTP)
    ACE_ERROR_RETURN((LM_ERROR,
                      ACE_TEXT ("SCTP was NOT installed when this binary was compiled.\n")
                      ACE_TEXT ("SOCK_STREAM_srv may still be run using TCP ")
                      ACE_TEXT ("via the '-t tcp' option.\n")),
                     1);
#endif

  // check that valid options were specified
  if (optsMgr._error) {
    ACE_OS::fprintf (stderr, "ERROR: %s\n", ACE_TEXT_ALWAYS_CHAR (optsMgr._error_message));
    return 1;
  }

  // this is the socket that the server will listen on
  ACE_SOCK_Acceptor acceptor_socket;

  // Create the address that we want to listen for connections on. If
  // server_accept_addr=INADDR_ANY (the default), SCTP will listen for
  // connections on all IP interfaces. If an address is specified,
  // SCTP will listen for connections on that address ONLY.
  ACE_INET_Addr serverAddr(optsMgr.server_port,
                           optsMgr.server_accept_addr);

  ACE_DEBUG((LM_DEBUG,
             ACE_TEXT ("(%P|%t) Accepting connections on port %u on interface %C using %C\n"),
             serverAddr.get_port_number(),
             (optsMgr.server_accept_addr == INADDR_ANY) ? "INADDR_ANY" : serverAddr.get_host_addr(),
             (optsMgr.test_transport_protocol == IPPROTO_SCTP) ? "IPPROTO_SCTP" : "IPPROTO_TCP"));

  // this operation creates a socket, binds the specified internet
  // address to it and calls listen. As this is a wrapper facade
  // approach, the ACE_OS::{socket,bind,listen} calls are invoked in
  // the implementation of open.
  if (acceptor_socket.open(serverAddr, 1,
                           AF_INET,
                           ACE_DEFAULT_BACKLOG,
                           optsMgr.test_transport_protocol) == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       ACE_TEXT ("%p\n"),
                       ACE_TEXT ("open")),
                      1);

  // this function checks that the port that was actually bound was
  // the port we asked for. Apparently some operating systems will
  // automatically select new ports if the specified port is currently
  // used.
  else if (acceptor_socket.get_local_addr(serverAddr) == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       ACE_TEXT ("%p\n"),
                       ACE_TEXT ("get_local_addr")),
                      1);

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%P|%t) starting server at port %d\n"),
              serverAddr.get_port_number()));

  // this is the stream object that will associated with a completed
  // connection (aka the data mode socket). It will be set when accept
  // is called below.
  ACE_SOCK_Stream new_stream;

  // a file decriptor set
  ACE_Handle_Set handle_set;
  // add the acceptor socket to the file descriptor set.
  handle_set.set_bit(acceptor_socket.get_handle());

  for (;;){

    ACE_Time_Value timeout(ACE_DEFAULT_TIMEOUT);
    ACE_Handle_Set temp = handle_set;

    // wait for connect() call from client. In the original test there
    // were two different acceptor sockets for two different
    // services. So select was needed to wait on both sockets
    // simultaneously. In this test we could just call accept on the
    // one socket.
    int result = ACE_OS::select(ACE_Utils::truncate_cast<int> ((intptr_t)acceptor_socket.get_handle()) +1,
                                (fd_set *) temp,
                                0,
                                0,
                                timeout);

    // check that select did not end with an error.
    if (result == -1)
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("(%P|%t) %p\n"),
                  ACE_TEXT ("select")));
    // check to see if select timed out.
    else if (result == 0){
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("(%P|%t) select timed out\n")));

    }
    else { // case where a file descriptor was actually set
      if (!(temp.is_set(acceptor_socket.get_handle()))){
        // CANNOT BE REACHED
        ACE_ERROR ((LM_ERROR,
                    ACE_TEXT ("(%P|%t) %p\n"),
                    ACE_TEXT ("select: NO ERROR BUT NO FD SET")));
      } else {
        // call accept to set up the new stream.
        if (acceptor_socket.accept(new_stream) == -1) {
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("%p\n"),
                      ACE_TEXT ("accept")));
          continue;
        }
        else{
          ACE_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("(%P|%t) spawning server\n")));

        }
        // Run the server.
        run_server (new_stream.get_handle ());
      }

    }

  }
  ACE_NOTREACHED (return 0;)
}
Exemple #19
0
	Game::Game(std::shared_ptr<Engine> engine) :
	FSMState(engine), 
#ifndef WIN32
		serverPID(0),
#endif
		connectedToServer(false), network(nullptr), levelManager(new LevelManager(engine))
	{
		callbacks['D'] = &Game::Disconnect;
		callbacks['L'] = &Game::LevelAction;

		if (engine->clientIsServer)
		{
			// create child process to run the server (if this client is the
			// one chosen to run the server)
#ifdef WIN32

			memset(&startupInfo, 0, sizeof startupInfo);
			memset(&procInfo, 0, sizeof procInfo);
			startupInfo.cb = sizeof startupInfo;
			std::string temp("TyphonServer ");
			temp += *engine->lobbyList;
			temp += " " + boost::lexical_cast<string>(GetNetworkIP(engine->serverIP));
			LPSTR argLine = const_cast<char*>(temp.c_str());

			int result;
#ifdef WIN64
#ifdef DEBUG // 64-bit build, Debug
			result = CreateProcess("../../bin/Server/Win64/Debug/TyphonServer64.exe", argLine, 
				nullptr, nullptr, true, CREATE_NEW_CONSOLE, nullptr, nullptr,
				&startupInfo, &procInfo);
#else // 64-bit build, Release
			result = CreateProcess("../../bin/Server/Win64/Release/TyphonServer64.exe", argLine, 
				nullptr, nullptr, true, CREATE_NEW_CONSOLE, nullptr, nullptr,
				&startupInfo, &procInfo);
#endif
#elif defined(WIN32)
#ifdef DEBUG // 32-bit build, Debug
			result = CreateProcess("../../bin/Server/Win32/Debug/TyphonServer32.exe", argLine, 
				nullptr, nullptr, true, CREATE_NEW_CONSOLE, nullptr, nullptr,
				&startupInfo, &procInfo);
#else // 32-bit build, Release
			result = CreateProcess("../../bin/Server/Win32/Release/TyphonServer32.exe", argLine, 
				nullptr, nullptr, true, CREATE_NEW_CONSOLE, nullptr, nullptr,
				&startupInfo, &procInfo);
#endif
#endif
			if(!result)
			{
				throw StateException("Error creating server process.\n");
			}
			//else
			//{
			//	auto waitResult = WaitForInputIdle(procInfo.hProcess, INFINITE);
			//}
#endif
#ifndef WIN32 // Linux
			std::unique_ptr<char[]> lobbyList(new char[engine->lobbyList->length() + 1]);
			strcpy(lobbyList.get(), engine->lobbyList->c_str());
			string server(boost::lexical_cast<string>(GetNetworkIP(engine->serverIP)));
			std::unique_ptr<char[]> serverAddr(new char[server.length() + 1]);
			strcpy(serverAddr.get(), server.c_str());
			char * const argList[] = { "TyphonServer", *lobbyList, *serverAddr, nullptr };

			serverPID = fork();
			if (serverPID == -1)
			{
				throw StateException("Error forking client.\n");
			}
			else if (serverPID == 0)
			{
				// this is the child
				// run the server program, sending the names & IPs
				// of the players as an argument


				// TODO Important -- these paths MUST be adjusted for final release
#ifdef DEBUG
				execvp("../../bin/Server/Linux/TyphonServer_D", argList);
#else
				execvp("../../bin/Server/Linux/TyphonServer", argList);
#endif
				// if we reach this point, something went wrong (exec doesn't return
				// otherwise)
				perror("execvp");
				Log("Exec call to create server failed.");
				throw StateException("Error exec'ing server.\n");
			}

			// if we reached this point, we're the parent
#endif
		}

		network.reset(Typhon::GetNetwork(Typhon::ENETCLIENT, PORT_NUMBER, &engine->serverIP));
		if (!network)
		{
			// TODO: Add some kind of notification if user can't initially connect
			throw StateException(
				"Error starting up network code (could not allocate or incompatible system).\n");
		}
		// set the level manager's network
		levelManager->network = network;
		
		connectedToServer = reinterpret_cast<NetworkENetClient*>(network.get())->ConnectToServer();
		if(!connectedToServer)
		{
			engine->eventQueue.push(FSM::RET_TO_LOBBY_FROM_GAME);
		}
	}
Exemple #20
0
int ACE_TMAIN(int argc, ACE_TCHAR **argv) {

    // size and count for transmissions
    int size = 0, count = -1;

    // the server's answer is a single byte
    char answer;

    // parse the <size> argument
    if ((argc < 2) || (((size = ACE_OS::strtol(argv[1], 0, 10)) < 1) ||
            (errno == EINVAL)))
        return printUsage(argv[0]);

    // take size as the number of MiB and create appropriate buffer
    size *= BASE;
    char *someData = new (std::nothrow) char[size];

    if (someData == 0)
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("%N:%l: Failed to allocate ")
                         ACE_TEXT ("data buffer.\n")), -1);

    // put someData in an auto_ptr so it gets deleted automatically
    auto_ptr<char> pSomeData(someData);

    // parse the <count> argument if available
    if ((argc == 3) && (((count = ACE_OS::strtol(argv[2], 0, 10)) < 1) ||
            (errno == EINVAL)))
        return printUsage(argv[0]);

    // the server listens on localhost on default port (from common.h)
    ACE_INET_Addr serverAddr(PORT, "localhost");

    ACE_SOCK_Stream stream;
    ACE_SOCK_Connector connector;

    // -1 is running indefinitely
    while ((count == -1) || (count-- != 0)) {

        // some output, that we know something is happening
        //ACE_DEBUG((LM_DEBUG, ACE_TEXT("%N:%l: Passes left: %i\n"), count));
        ACE_DEBUG((LM_DEBUG, ACE_TEXT(".")));

        // connect to the server and get the stream
        if (connector.connect(stream, serverAddr) == -1) {
          ACE_ERROR((LM_ERROR,
                     ACE_TEXT("%N:%l: Failed to connect to ")
                     ACE_TEXT ("server. (errno = %i: %m)\n"), ACE_ERRNO_GET));
            break;
        }

        try {

            // send the request to the server (number of MiB in the next call)
            // Note: only use the sizeof and pointer to int on compatible
            //       platforms (i.e. little-endian/big-endian, data type size)
            if (stream.send_n(&size, sizeof(size), &connTimeout) != sizeof(size)) {
                ACE_ERROR((LM_ERROR, ACE_TEXT("%N:%l: Failed to  send ")
                           ACE_TEXT ("request. (errno = %i: %m)\n"), ACE_ERRNO_GET));
                throw 1;
            }

            // receive the answer
            if (stream.recv_n(&answer, sizeof(answer), &connTimeout) != 1) {
              ACE_ERROR((LM_ERROR, ACE_TEXT("%N: %l: Failed to receive ")
                         ACE_TEXT ("1st response. (errno = %i: %m)\n"), ACE_ERRNO_GET));
                throw 1;
            }

            // server answer, 'K" indicates a positive answer
            if (answer == 'K') {

                // send a huge message to the server
                if (stream.send_n(someData, size, &connTimeout) != size) {
                  ACE_ERROR((LM_ERROR, ACE_TEXT("%N:%l: Failed to send ")
                             ACE_TEXT ("someData. (errno = %i: %m)\n"), ACE_ERRNO_GET));
                    throw 1;
                }

                // get an answer
                if (stream.recv_n(&answer, sizeof(answer), &connTimeout) != 1) {
                  ACE_ERROR((LM_ERROR, ACE_TEXT("%N: %l: Failed to receive ")
                             ACE_TEXT ("2nd response. (errno = %i: %m)\n"), ACE_ERRNO_GET));
                    throw 1;
                }

                // check the answer
                if (answer != 'K') {
                    cout << "The server was unable to process the data."
                         << endl;
                }
            }
        } catch (...) {
            // ok we know an error occurred, we need to close the socket.
            // The we'll try again.
        }

        // close the current stream
        if (stream.close() == -1) {
          ACE_ERROR((LM_ERROR, ACE_TEXT("%N:%l: Failed to close ")
                     ACE_TEXT ("socket. (errno = %i: %m)\n"), ACE_ERRNO_GET));
            break;
        }
    } // while

    cout << "Bye. Bye" << endl;
    return 0;
}
Exemple #21
0
int ACE_TMAIN (int argc, ACE_TCHAR **argv){

  // Initialize the options manager
  Options_Manager optsMgr(argc, argv, ACE_TEXT ("client-opts"));

  // show usage if requested
  if (optsMgr._usage) {
    optsMgr._show_usage(stderr, ACE_TEXT ("client-opts"));
    return 1;
  }

  // If SCTP is not installed then terminate the program, unless TCP
  // was specified.
#ifndef ACE_HAS_SCTP
  if (optsMgr.test_transport_protocol == IPPROTO_SCTP)
    ACE_ERROR_RETURN((LM_ERROR,
                      ACE_TEXT ("SCTP was NOT installed when this binary was compiled.\nSOCK_STREAM_clt may still be run using TCP via the '-t tcp' option.\n")),
                     1);
#endif

  // check that valid options were specified
  if (optsMgr._error) {
    ACE_OS::fprintf (stderr, "ERROR: %s\n", ACE_TEXT_ALWAYS_CHAR (optsMgr._error_message));
    return 1;
  }


  // Create the address that we want the client to connect to
  ACE_INET_Addr serverAddr(Options_Manager::server_port,
                           Options_Manager::server_host);

  // Create the address that we want the client to connect FROM
  ACE_INET_Addr clientAddr(Options_Manager::client_port,
                           Options_Manager::client_connect_addr);

  // object that manages the connection to the server
  ACE_SOCK_Connector connector;

  // object that manages the data xfer between the client and server
  ACE_SOCK_Stream dataStream;

  // connect to the server
  if (connector.connect (dataStream,
                         serverAddr,
                         0,clientAddr, 0, 0, 0, // ALL DEFAULT ARGUMENTS
                         Options_Manager::test_transport_protocol) == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       ACE_TEXT ("(%P|%t) %p\n"),
                       ACE_TEXT ("connection failed")),
                      1);

  // run the test
  ACE_SCTP::HIST testResultsHistogram = 0;
  // connection is closed by runTest* functions
  testResultsHistogram = runTest(dataStream);

  // report out the test statistics.
  // all histograms created are placed onto a linked list that report()
  // can access. So the histogram created in one of the *_test() functions
  // will be reported out by the report() call
  if (testResultsHistogram)
    ACE_SCTP::report();

  return 0;
}
int UDPGenerator::writedatagram(const ACE_TCHAR * remotehost,
                                u_short remoteport)
{
    // We are using scatter/gather to send the message header and/*{{{*/
    // message body using 2 buffers

    // create a message block for the message header
    ACE_Message_Block* msg = 0;
    ACE_NEW_RETURN(msg, ACE_Message_Block(100), -1);
    const char rawMsg [] = "To be or not to be.";
    // Copy buf into the Message_Block and update the wr_ptr ().
    msg->copy(rawMsg, ACE_OS::strlen(rawMsg) + 1);

    // create a message block for the message body
    ACE_Message_Block* body = 0;
    ACE_NEW_RETURN(body, ACE_Message_Block(100), -1);
    ACE_OS::memset(body->wr_ptr(), 'X', 100);
    body->wr_ptr(100); // always remember to update the wr_ptr()

    msg->cont(body);

    // do the asynch send
    size_t number_of_bytes_sent = 0;
    ACE_INET_Addr serverAddr(remoteport, remotehost);
    int res = this->wd_.send(
                  msg, number_of_bytes_sent,
                  0,
                  serverAddr,
                  this->act_);

    switch (res)
    {
    case 0:
        // this is a good error.  The proactor will call our handler when the
        // send has completed.
        break;
    case 1:
        // actually sent something, we will handle it in the handler callback
        ACE_DEBUG ((LM_DEBUG, "********************\n"));
        ACE_DEBUG ((LM_DEBUG,
                    "%s = %d\n",
                    "bytes sent immediately",
                    number_of_bytes_sent));
        ACE_DEBUG ((LM_DEBUG, "********************\n"));
        res = 0;
        break;
    case -1:
        // Something else went wrong.
        ACE_ERROR ((LM_ERROR,
                    "%p\n",
                    "ACE_Asynch_Write_Dgram::recv"));
        // the handler will not get called in this case so lets clean up our msg
        msg->release ();
        break;
    default:
        // Something undocumented really went wrong.
        ACE_ERROR ((LM_ERROR,
                    "%p\n",
                    "ACE_Asynch_Write_Dgram::recv"));
        msg->release ();
        break;
    }
    return res;
}/*}}}*/
Exemple #23
0
bool MgServerConnectionImp::Connect(const char* ipAddress, int portno)
{
    if (mServer)
    {
        Disconnect();
    }

    // Create the ACE stream
    mServer = new ACE_SOCK_Stream();

    ACE_INET_Addr serverAddr(portno, ipAddress);

    ACE_SOCK_Connector connector;

    // Server connection backlog could be overrun during high connections.
    // Retry 5 times with a short delay between each attempt.
    const ACE_Time_Value timeout(2); // 2 seconds
    int nRetries = 5;
    int connectResult = -1;

    while (nRetries > 0
        && -1 == (connectResult = connector.connect(*mServer, serverAddr, &timeout)))
    {
        int status = ACE_OS::set_errno_to_wsa_last_error();

        switch (status)
        {
            // Retry on these.
            case ETIMEDOUT:
            case ECONNRESET:
            case EAGAIN:
                --nRetries;
                break;

            // Bail immediately on any other.
            // case ECONNREFUSED:
            // case EHOSTDOWN:
            // case EHOSTUNREACH:
            // case ENETDOWN:
            // case ENETUNREACH:
            case ENOTCONN: // most likely
            default:
                nRetries = 0;
                break;
        }
    }

    if (-1 == connectResult)
    {
        int err = ACE_OS::last_error();
        MG_UNUSED_ARG(err);

        // We failed to connect so we must clean this up differently then just relying on the
        // desturctor because the Disconnect() method called by the destructor will try and
        // send a control packet which we don't want.
        mServer->close_writer();
        mServer->close_reader();
        mServer->close();

        delete mServer;
        mServer = NULL;
        return false;
    }


    // TODO: Send the Test request to make sure there is real Mg server

    // Connected fine
    return true;
}
Exemple #24
0
int main(int argc,char* argv[])
{	
	/*****************************************/
	//从命令行参数读取配置文件
	/*****************************************/
#if 1
	if(argc!=2)
	{
		perror("args error!");
		exit(1);
	}
	Configure conf(argv[1]);
#endif
#if 0
	Configure conf("conf.txt");
#endif
	Index mIndex(conf.getConf("mydict"));
	cout<<"加载配置成功……"<<endl;


	/*****************************************/
	//初始化线程池
	/*****************************************/
	Threadpool threadpool(5,4);
	threadpool.start();
	cout<<"线程池创建成功……"<<endl;


	/*****************************************/
	//初始化TCP服务器
	/*****************************************/
	const string IP =conf.getConf("myip");
	uint16_t PORT = atoi(conf.getConf("myport").c_str());
	InetAddress serverAddr(IP,PORT);
	InetAddress clientAddr;
	Socket socket;
	int servfd = socket.fd();
	socket.ready(serverAddr);
	char buf[32];
	cout<<"服务器启动成功……"<<endl;


	/*****************************************/
	//循环接收请求,并封装成任务,并加入线程池
	/*****************************************/
	Task *ptask ;
	cout<<"等待客户端连接"<<endl;
	while(1)
	{
		SocketIO sockIO(servfd);
		memset(buf,'\0',32);
		sockIO.readn(buf,32,clientAddr);
		/******************************
		 *log
		 */
		cout<<"IP:"<<clientAddr.ip()<<endl;
		cout<<"PORT:"<<clientAddr.port()<<endl;
		cout<<"------------------"<<endl;

		std::string str(buf);
		ptask = new Task(servfd,clientAddr,str,mIndex);
		threadpool.addTask(ptask);
	}
	return 0;
}