Esempio n. 1
9
Peer* ClientHost::Connect(
  std::string server_ip,
  uint16_t port,
  size_t channel_count
) {
  CHECK(_state == STATE_INITIALIZED);

  ENetAddress address;
  if (enet_address_set_host(&address, server_ip.c_str()) != 0) {
    // THROW_ERROR("Unable to set enet host address!");
    return NULL;
  }
  address.port = port;  // XXX: type cast.

  ENetPeer* enet_peer = enet_host_connect(_host, &address, channel_count, 0);
  if (enet_peer == NULL) {
    // THROW_ERROR("Enet host is unable to connect!");
    return NULL;
  }

  Peer* peer = Host::_GetPeer(enet_peer);
  CHECK(peer != NULL);

  return peer;
}
Esempio n. 2
3
static int initEnet(const char *host_ip, const int host_port, ServerData *data)
{
   ENetAddress address;
   assert(data);

   if (enet_initialize() != 0) {
      fprintf (stderr, "An error occurred while initializing ENet.\n");
      return RETURN_FAIL;
   }

   address.host = ENET_HOST_ANY;
   address.port = host_port;

   if (host_ip)
      enet_address_set_host(&address, host_ip);

   data->server = enet_host_create(&address,
         32    /* max clients */,
         2     /* max channels */,
         0     /* download bandwidth */,
         0     /* upload bandwidth */);

   if (!data->server) {
      fprintf (stderr,
            "An error occurred while trying to create an ENet server host.\n");
      return RETURN_FAIL;
   }

   /* enable compression */
   data->server->checksum = enet_crc32;
   enet_host_compress_with_range_coder(data->server);

   return RETURN_OK;
}
Esempio n. 3
0
void CC_Client::connect(const char *host=HOST, uint16_t port=PORT) {
    if (connected) {
        printf("Connected already.\n");
        return;
    }
    
    enet_address_set_host(&address, host);
    address.port = port;
    
    peer = enet_host_connect(client, &address, 2, 0);
    
    if (peer == NULL) {
        fprintf(stderr, "No available peers to connect\n");
        exit(EXIT_FAILURE);
    }
    
    if (enet_host_service(client, &evt, 5000) > 0
        && evt.type == ENET_EVENT_TYPE_CONNECT) {
        printf("Connected to server %s:%u\n", HOST, PORT);
        connected = true;
    } else {
        enet_peer_reset(peer);
        printf("Connection failed to %s:%u\n", HOST, PORT);
    }
    
    //~ conn_t_ret = pthread_create(&conn_t, NULL, CC_Client::loop, (void*)this);
}
Esempio n. 4
0
bool CNetClientSession::Connect(u16 port, const CStr& server)
{
	ENSURE(!m_Host);
	ENSURE(!m_Server);

	// Create ENet host
	ENetHost* host = enet_host_create(NULL, 1, CHANNEL_COUNT, 0, 0);
	if (!host)
		return false;

	// Bind to specified host
	ENetAddress addr;
	addr.port = port;
	if (enet_address_set_host(&addr, server.c_str()) < 0)
		return false;

	// Initiate connection to server
	ENetPeer* peer = enet_host_connect(host, &addr, CHANNEL_COUNT, 0);
	if (!peer)
		return false;

	m_Host = host;
	m_Server = peer;

	m_Stats = new CNetStatsTable(m_Server);
	if (CProfileViewer::IsInitialised())
		g_ProfileViewer.AddRootTable(m_Stats);

	return true;
}
Esempio n. 5
0
VALUE renet_connection_initialize(VALUE self, VALUE host, VALUE port, VALUE channels, VALUE download, VALUE upload)
{
  rb_funcall(mENet, rb_intern("initialize"), 0);
  Connection* connection;

  /* Now that we're releasing the GIL while waiting for enet_host_service 
     we need a lock to prevent potential segfaults if another thread tries
     to do an operation on same connection  */
  VALUE lock = rb_mutex_new();
  rb_iv_set(self, "@lock", lock); 
  rb_mutex_lock(lock);

  Data_Get_Struct(self, Connection, connection);
  Check_Type(host, T_STRING);
  if (enet_address_set_host(connection->address, StringValuePtr(host)) != 0)
  {
    rb_raise(rb_eStandardError, "Cannot set address");
  }
  connection->address->port = NUM2UINT(port);
  connection->channels = NUM2UINT(channels);
  connection->online = 0;
  connection->host = enet_host_create(NULL, 1, connection->channels, NUM2UINT(download), NUM2UINT(upload));
  if (connection->host == NULL)
  {
    rb_raise(rb_eStandardError, "Cannot create host");
  }
  rb_iv_set(self, "@total_sent_data", INT2FIX(0)); 
  rb_iv_set(self, "@total_received_data", INT2FIX(0));
  rb_iv_set(self, "@total_sent_packets", INT2FIX(0));
  rb_iv_set(self, "@total_received_packets", INT2FIX(0));

  rb_mutex_unlock(lock);
  return self;
}
void NetworkController::initEnet() {
	if( enet_initialize() != 0){
		root->fatalError("NetController", "Cannot initialise ENet");
	};
	
	root->sout << "Attempting to create host..." << endl;
	
	if( root->confMgr.varExists("host_address") ){
		enet_address_set_host( &enetAddress, root->confMgr.getVarS("host_address").c_str() );
		
		root->sout << "Binding to configured address " << root->confMgr.getVarS("host_address") <<endl;
	}else{
		enetAddress.host = ENET_HOST_ANY;
		root->sout << "Binding to any available address" << endl;
	}
	
	if( root->confMgr.varExists("host_port") ){
		enetAddress.port = root->confMgr.getVarI("host_port");
	}else{
		enetAddress.port = HOST_PORT_DEFAULT;
	}
	
	root->sout << "Binding to port " << enetAddress.port << endl;
	
	enetHost = enet_host_create(&enetAddress, (root->confMgr.varExists("max_clients")) ? (root->confMgr.getVarI("max_clients")) : MAX_CLIENTS_DEFAULT, 2, 0, 0);
	
	if(enetHost == NULL) {
		root->fatalError("NetController", "Cannot create ENet host");
	}
}
Esempio n. 7
0
NetClient::NetClient(const std::string& ip)
:
    me                (0),
    server            (0),
    exit              (false),
    is_game           (false),
    game_start        (false),
    game_end          (false),
    room_data_change  (false),
    player_data_change(false),
    level_change      (false),
    updates_change    (0),
    ourself           (players.begin()) // will crash if dereferenced if empty
{
    // 0 = Client, 1 = one connection at most (to server), 0, 0 = unlim. bandw.
    //
    // #############################################################
    // # NOTE: If you get a compiler error for the following line, #
    // #  check your enet version. Lix assumes you have enet 1.3.  #
    // #############################################################
    me = enet_host_create(0, 1, LEMNET_CHANNEL_MAX, 0, 0);

    ENetAddress address;
    enet_address_set_host(&address, ip.c_str());
    address.port = gloB->server_port;

    server = enet_host_connect(me, &address, LEMNET_CHANNEL_MAX, 0);
}
Esempio n. 8
0
bool NNetwork::Connect(std::string i_HostName, unsigned int Port)
{
    if (Host)
    {
        Disconnect();
    }
    HostName = i_HostName;
    Address.port = Port;
    enet_address_set_host(&Address, HostName.c_str());

    Host = enet_host_connect(Client,&Address,2,0);
    if (!Host)
    {
        std::stringstream Message;
        Message << "Failed to connect to host " << HostName << " on port " << Port << "!";
        GetGame()->GetLog()->Send("NETWORK",0,Message.str());
        return 1;
    }
    ENetEvent Event;
    if (enet_host_service(Client, &Event, 2500) > 0 && Event.type == ENET_EVENT_TYPE_CONNECT)
    {
        std::stringstream Message;
        Message << "Successfully connected to " << HostName << " on port " << Port << ".";
        GetGame()->GetLog()->Send("NETWORK",2,Message.str());
        return 0;
    } else {
        std::stringstream Message;
        Message << "Failed to connect to host " << HostName << " on port " << Port << "!";
        GetGame()->GetLog()->Send("NETWORK",0,Message.str());
        Host = NULL;
        return 1;
    }
    return 1;
}
int NetworkManager::connexionToHost(std::string url,int port)
{
	enet_address_set_host (& address,url.c_str());
	address.port = port;
	peer = enet_host_connect (client, & address, 2, 0);
	if (peer == NULL)
	{
		return 1;
	}
	if (enet_host_service (client, &eventClient, 1000) > 0 && eventClient.type == ENET_EVENT_TYPE_CONNECT)
	{
		isConnectedflag = true;
		endThread = false;
		thread = boost::thread(&NetworkManager::threadConnexion, (void *) this);
		return 0;
	}
	else
	{
		/* Either the 5 seconds are up or a disconnect event was */
		/* received. Reset the peer in the event the 5 seconds   */
		/* had run out without any significant event.            */
		enet_peer_reset (peer);
		return 2 ;
	}
}
Esempio n. 10
0
int resolverloop(void * data)
{
    resolverthread *rt = (resolverthread *)data;
    for(;;)
    {
        SDL_SemWait(resolversem);
        SDL_LockMutex(resolvermutex);
        if(resolverqueries.empty())
        {
            SDL_UnlockMutex(resolvermutex);
            continue;
        }
        rt->query = resolverqueries.pop();
        rt->starttime = lastmillis;
        SDL_UnlockMutex(resolvermutex);
        ENetAddress address = { ENET_HOST_ANY, CUBE_SERVINFO_PORT };
        enet_address_set_host(&address, rt->query);
        SDL_LockMutex(resolvermutex);
        resolverresult &rr = resolverresults.add();
        rr.query = rt->query;
        rr.address = address;
        rt->query = NULL;
        rt->starttime = 0;
        SDL_UnlockMutex(resolvermutex);
    };
    return 0;
};
Esempio n. 11
0
void networkEngine::serverSetup()
{
    //gameEngine *gameE = gameEngine::Instance();
    boost::shared_ptr<gameEngine> gameE = gameEngine::Instance();

    /* Bind the server to the default localhost.     */
    /* A specific host address can be specified by   */
    /* enet_address_set_host (& address, "x.x.x.x"); */

// Old Pre-GUI ip address input code
//    string ipAddress;
//    cout << "IP Address to bind to:" << endl;
//    cin >> ipAddress;

    listenAddress.host = enet_address_set_host (& listenAddress, ipAddress.c_str());
//    listenAddress.host = enet_address_set_host (& listenAddress, ENET_HOST_ANY);

    /* Bind the server to port 1234. */
    listenAddress.port = 1234;

    server = enet_host_create (& listenAddress /* the address to bind the server host to */,
                               32      /* allow up to 32 clients and/or outgoing connections */,
                               2	/* allows up to 2 channels, 0, 1*/,
                               0      /* assume any amount of incoming bandwidth */,
                               0      /* assume any amount of outgoing bandwidth */);
    if (server == NULL)
    {
        logMsg("An error occurred while trying to create an ENet server host.");
        exit (EXIT_FAILURE);
    }
    gameE->setServerRunning(true);
}
Esempio n. 12
0
void menu_connect_start(component *c, void *userdata) {
    scene *s = userdata;
    connect_menu_data *local = menu_get_userdata(c->parent);
    ENetAddress address;
    const char *addr = textinput_value(local->addr_input);
    s->gs->role = ROLE_CLIENT;

    // Free old saved address, and set new
    free(settings_get()->net.net_connect_ip);
    settings_get()->net.net_connect_ip = strdup(addr);

    // Set up enet host
    local->host = enet_host_create(NULL, 1, 2, 0, 0);
    if(local->host == NULL) {
        DEBUG("Failed to initialize ENet client");
        return;
    }

    // Disable connect button and address input field
    component_disable(local->connect_button, 1);
    component_disable(local->addr_input, 1);
    menu_select(c->parent, local->cancel_button);

    // Set address
    enet_address_set_host(&address, addr);
    address.port = settings_get()->net.net_connect_port;

    ENetPeer *peer = enet_host_connect(local->host, &address, 2, 0);
    if(peer == NULL) {
        DEBUG("Unable to connect to %s", addr);
        enet_host_destroy(local->host);
        local->host = NULL;
    }
    time(&local->connect_start);
}
Esempio n. 13
0
    NetManager::NetManager(bool isServer, const FAWorld::PlayerFactory& playerFactory) : mPlayerFactory(playerFactory)
    {
        assert(singletonInstance == NULL);
        singletonInstance = this;

        enet_initialize();

        mAddress.port = 6666;

        mIsServer = isServer;

        if(isServer)
        {
            mAddress.host = ENET_HOST_ANY;
            mHost = enet_host_create(&mAddress, 32, 2, 0, 0);
        }
        else
        {
            enet_address_set_host(&mAddress, "127.0.0.1");
            mHost = enet_host_create(NULL, 32, 2, 0, 0);

            mServerPeer = enet_host_connect(mHost, &mAddress, 2, 0);

            ENetEvent event;

            if(enet_host_service(mHost, &event, 5000))
            {
                std::cout << "connected" << std::endl;
            }
            else
            {
                std::cout << "connection failed" << std::endl;
            }
        }
    }
Esempio n. 14
0
void *Network::readThread(void *context)
{
    struct thread_args *args = (struct thread_args *)context;
    char *ip = args->ip;
    Network *instance = args->instance;
    ENetEvent event;
    ENetAddress address;

    client = enet_host_create(NULL, 1, 1, 0, 0);
    if (client == NULL)
        return (void*)1;

    enet_address_set_host (&address, ip);
    address.port = 1400;
    server = enet_host_connect (client, &address, 1, 0);
    if (server == NULL)
        return (void*)2;

    if (!(enet_host_service (client, &event, 5000) > 0 && event.type == ENET_EVENT_TYPE_CONNECT))
        return (void*)3;
    emit instance->connected();

    while(true) {
        pthread_mutex_lock(&net_mutex);
        enet_host_service (client, &event, 0);
        pthread_mutex_unlock(&net_mutex);
        switch (event.type) {
        case ENET_EVENT_TYPE_CONNECT:
            server = event.peer;
            emit instance->connected();
            break;
        case ENET_EVENT_TYPE_RECEIVE:
            switch(event.packet->data[0]) {
            case SET_MEASURED_VALUES:
                float values[3];
                memcpy(values, event.packet->data + 1, sizeof(float) * 3);
                emit instance->setMeasuredValues(values[0], values[1], values[2]);
                break;
            case SET_CPU_USAGE:
                emit instance->setCPUUsage(event.packet->data[1]);
                break;
            case SET_MEMORY_USAGE:
                emit instance->setMemoryUsage(event.packet->data[1]);
                break;
            }
            enet_packet_destroy(event.packet);
            break;
        case ENET_EVENT_TYPE_DISCONNECT:
            server = NULL;
            emit instance->disconnect();
            break;
        default:
            break;
        }
        usleep(100);
    }
    return (void*)0;
}
Esempio n. 15
0
int main (int argc, char ** argv)
{
  if (enet_initialize () != 0)
  {
    fprintf (stderr, "An error occurred while initializing ENet.\n");
    return EXIT_FAILURE;
  }
  atexit (enet_deinitialize);

  printf("creating host\n");

  host = enet_host_create (NULL /* create a client host */,
                              1 /* only allow 1 outgoing connection */,
                              2 /* allow up 2 channels to be used, 0 and 1 */,
                              57600 / 8 /* 56K modem with 56 Kbps downstream bandwidth */,
                              14400 / 8 /* 56K modem with 14 Kbps upstream bandwidth */);
  if (host == NULL)
  {
    fprintf (stderr,
              "An error occurred while trying to create an ENet client host.\n");
    exit (EXIT_FAILURE);
  }

  ENetAddress address;
  enet_address_set_host (& address, "localhost");
  address.port = SOCKK;

  printf("connecting to server...\n");

  ENetPeer *peer = enet_host_connect (host, & address, 2, 0);

  if (peer == NULL)
  {
    fprintf (stderr,
    "No available peers for initiating an ENet connection.\n");
    exit (EXIT_FAILURE);
  }

#ifdef __EMSCRIPTEN__
#if USE_IFRAME
  emscripten_run_script("console.log('adding iframe');"
                        "var iframe = document.createElement('iframe');"
                        "iframe.src = 'server.html';"
                        "iframe.width = '100%';"
                        "iframe.height = '33%';"
                        "document.body.appendChild(iframe);"
                        "console.log('added.');");
#endif
#endif

#ifdef __EMSCRIPTEN__
  emscripten_set_main_loop(main_loop, 3, 1);
#else
  while (1) main_loop();
#endif

  return 1;
}
Esempio n. 16
0
void networkEngine::clientConnect()
{
    //gameEngine *gameE = gameEngine::Instance();
    boost::shared_ptr<gameEngine> gameE = gameEngine::Instance();

    if (!clientEstablishedConnection)
    {

        client = enet_host_create (NULL /* create a client host */,
                                   4 /* only allow 1 outgoing connection */,
                                   2 /* allow up to 2 channels to be used, 0 and 1*/,
                                   0 /* 56K modem with 56 Kbps downstream bandwidth */,
                                   0 /* 56K modem with 14 Kbps upstream bandwidth */);

        if (client == NULL)
        {
            logMsg("An error occurred while trying to create an ENet client host.");
            exit (EXIT_FAILURE);
        }

// Old Pre-GUI ipAddress input code
//    string ipAddress;
//    cout << "IP Address: " << endl;
//    cin >> ipAddress;

        /* Connect to some.server.net:1234. */
        enet_address_set_host (& serverAddress, ipAddress.c_str());
        serverAddress.port = 1234;

        /* Initiate the connection, allocating the two channels 0 and 1. */
        peer = enet_host_connect (client, & serverAddress, 2, 0);

        if (peer == NULL)
        {
            logMsg("No available peers for initiating an ENet connection.");
            exit (EXIT_FAILURE);
        }

        /* Wait up to 5 seconds for the connection attempt to succeed. */
        if (enet_host_service (client, & event, 5000) > 0 &&
                event.type == ENET_EVENT_TYPE_CONNECT)
        {
            logMsg("Connection to " +ipAddress +":1234 succeeded.");
            clientEstablishedConnection = true; // Tells other code that this instance is a network client
        }
        else
        {
            /* Either the 5 seconds are up or a disconnect event was */
            /* received. Reset the peer in the event the 5 seconds   */
            /* had run out without any significant event.            */
            enet_peer_reset (peer);

            logMsg("Connection to " +ipAddress +":1234 failed.");
        }
        gameE->setClientRunning(true);
        clientEstablishedConnection = true;
    }
}
Esempio n. 17
0
File: main.c Progetto: atheros/svc
/**
 * COMMAND /connect host port
 *
 * Initiate connection to svceserver.
 */
static int cmd_connect(int argc, dstring** argv) {
	ENetAddress address;
	char buffer[100];

	/* check if client is in correct state to connect */
	if (client.state != SVCECLIENT_STATE_DISCONNECTED) {
		if (client.state == SVCECLIENT_STATE_CONNECTED) {
			fprintf(stderr, "Already connected.\n");
		} else if (client.state == SVCECLIENT_STATE_CONNECTING) {
			fprintf(stderr, "Already trying to connect.\n");
		} else {
			fprintf(stderr, "Unknown client state.\n");
		}
		return 0;
	}

	if (argc != 3) {
		fprintf(stderr, "usage: /connect host port\n");
		return 0;
	}

	/* resolve host */
	address.port = atoi(argv[2]->data);
	if (enet_address_set_host(&address, argv[1]->data)) {
		fprintf(stderr, "Failed to resolve '%s'\n", argv[1]->data);
		return 0;
	} else {
		dcpy(client.server_host_name, argv[1]);
		buffer[0] = 0;
		enet_address_get_host_ip(&address, buffer, 100);
		dcpycs(client.server_host_addr, buffer);
		client.server_host_port = address.port;
	}

	mutex_lock(&client.network_lock);
	/* create host */
	client.host = enet_host_create(NULL, 1, 2, 0, 0);
	if (client.host == NULL) {
		mutex_unlock(&client.network_lock);
		fprintf(stderr, "An error occurred while trying to create enet host.\n");
		return 0;
	}

	/* initiate connection */
	client.client = enet_host_connect(client.host, &address, 2, 0);
	if (client.client == NULL) {
		enet_host_destroy(client.host);
		mutex_unlock(&client.network_lock);
		fprintf(stderr, "No available peers to initiate a connection.\n");
		return 0;
	}

	mutex_unlock(&client.network_lock);

	client.state = SVCECLIENT_STATE_CONNECTING;
	msg_state();
	return 0;
}
Esempio n. 18
0
 bool Client::set_ip(std::string new_ip)
 {
     if(!_V_is_running and !enet_address_set_host(&_V_address,new_ip.c_str()))
     {
         _V_ip=new_ip;
         return true;
     }
     return false;
 }
Esempio n. 19
0
int module_start (Q5Module* self)
{
  int i;  
  uint32_t gameEngineSrvNo;
  ENetAddress address;

  if (enet_initialize () != 0)
  {
    eclogger_msg (LL_ERROR, properties.name, "server", "could not initialize enet");
    return FALSE;
  }
  
  enet_address_set_host (&address, self->host);
  address.port = self->port;
  
  self->server = enet_host_create (&address, 32, 2, 0, 0);      
  if (!self->server)
  {
    enet_deinitialize();

    eclogger_msg (LL_ERROR, properties.name, "server", "can't start enet server");
    return FALSE;
  }

  eclogger_fmt (LL_DEBUG, properties.name, "server", "listen '%s' on port '%u'", self->host, self->port);

  self->threads = eclist_new ();
  
  self->done = FALSE;
  
  for (i = 0; i < 1; i++)
  {
    EcThread thread = ecthread_new ();
    
    eclist_append(self->threads, thread);
    
    ecthread_start(thread, module_thread_run, self);
  }

  gameEngineSrvNo = q5core_getModuleId (self->core, "GAME_E");
  
  if (gameEngineSrvNo == 0)
  {
    eclogger_fmt (LL_WARN, properties.name, "server", "no game engine available");
  }
  
  self->entities = gse_create (self->server, gameEngineSrvNo, "Lobo's geiler server");
  
  gse_addRealm (self->entities, "the shire");
  
  ecmessages_add (self->instance->msgid, Q5_DATA_GET, module_callback_get, self);

  return TRUE;
}
Esempio n. 20
0
/*
    @brief Connect the client to a remote server. createClient() should be called first.
    @return True for success.
*/
bool clientConnect(const char* hostName)
{
    if (client == nullptr)
    {
        return false;
    }

    if (strcmp(hostName, "localhost") == 0)
    {
        enet_address_set_host(&address, "127.0.0.1");
    }
    else
    {
        enet_address_set_host(&address, hostName);
    }
    address.port = PORT;
    
    peer = enet_host_connect(client, &address, NUM_CHANNELS, CHANNEL_ID);

    return (peer != nullptr);
}
	void ClientTransmissionManager::Connect()
	{
		boost::mutex::scoped_lock lock(this->mHostMutex);

		std::stringstream s;

		this->mAddress.host = ENET_HOST_ANY;
		this->mAddress.port = this->mPort;

        if(enet_address_set_host(&this->mAddress, this->mHost.c_str())==0)
        {
			s << "Resolved hostname.";
			this->GetClientSessionManager().Log(s);

			if(this->mClient==NULL)
			{
				this->mClient = enet_host_create(
				NULL,
				this->mClientLimit,
				this->mDownstreamLimit,
				this->mUpstreamLimit);
			}

			if(this->mClient!=NULL)
			{
				s << "Connected to network.";
				this->GetClientSessionManager().Log(s);

				this->mPeer = enet_host_connect(this->mClient,&this->mAddress, 5);
				if (this->mPeer == NULL)
				{
					s << "Server not found.";
					this->GetClientSessionManager().Log(s);
				}
				else
				{
					this->mPeer->data=NULL;
					s << "Server found.";
					this->GetClientSessionManager().Log(s);
				}
			}
			else
			{
				s << "Unable to connect to network.";
				this->GetClientSessionManager().Log(s);
			}
        }
        else
        {
			s << "Couldn't resolve hostname.";
			this->GetClientSessionManager().Log(s);
        }
	}
Esempio n. 22
0
    void Host::connect(const std::string &hostname, unsigned int port)
    {
        // set the address of the server to connect to
        enet_address_set_host(&mAddress, hostname.c_str());
        mAddress.port = port;

        // connect to the server
#ifdef ENET_VERSION
        mServer = enet_host_connect(mClient, &mAddress, 0, 1);
#else
        mServer = enet_host_connect (mClient, &mAddress, 1);
#endif
    }
Esempio n. 23
0
bool network_connect( ENetHost* socket, const char* server, int port, int timeout )
{
	ENetAddress address;
	ENetEvent ev;

	if( socket == 0 )
		return false;

	enet_address_set_host( &address, server );
	address.port = port;
	enet_host_connect( socket, &address, 1, 0 );
	return (enet_host_service( socket, &ev, timeout) > 0 && ev.type == ENET_EVENT_TYPE_CONNECT);
}
Esempio n. 24
0
void NetClient::Connect(const char* connect)
{
	m_enetclient = enet_host_create(NULL, 1, 1, 350000, 95000); // This is 3 megabit d/l, .75 megabit upload. Should be the lowest common denominator of internet connection today.

	ENetAddress address;
	enet_address_set_host(&address, connect);
	address.port = 51072;

	m_enetpeer = enet_host_connect(m_enetclient, &address, 1, 0);

#ifdef _DEBUG
	enet_peer_timeout(m_enetpeer, UINT32_MAX, UINT32_MAX, UINT32_MAX);
#endif
}
Esempio n. 25
0
	bool Client::Connect(const std::string &ip)
	{
		ENetAddress address;
		ENetEvent event;
		
		enet_address_set_host(&address, ip.c_str());
		address.port = _port;
		
		RN_ASSERT((_host = enet_host_create(NULL, 1, 2, 0, 0)), "Enet couldn't create client!");
		RN_ASSERT((_peer = enet_host_connect(_host, &address, 2, 0)), "Enet couldn't create a peer!");
		
		_connected = (enet_host_service(_host, &event, 5000) > 0 && event.type == ENET_EVENT_TYPE_CONNECT);
		return _connected;
	}
Esempio n. 26
0
/** Initialises the client. This function tries to connect to the server.
 */
bool NetworkManager::initClient(const char* hostName, int portHost)
{
    m_host = enet_host_create (NULL /* create a client host */,
                               1    /* only allow 1 outgoing connection */,
                               0    /* channel limit */,
                               0    /* downstream bandwidth unlimited   */,
                               0    /*  upstream bandwidth unlimited    */ );

    if (m_host == NULL)
    {
        fprintf (stderr,
            "An error occurred while trying to create an ENet client host.\n");
        return false;
    }

    ENetAddress address;
    ENetEvent event;
    ENetPeer *peer;

    enet_address_set_host (& address, hostName);
    address.port = portHost;

    /* Initiate the connection, allocating the two channels 0 and 1. */
    peer = enet_host_connect (m_host, &address, 2, 0);

    if (peer == NULL)
    {
        fprintf(stderr,
                "No available peers for initiating an ENet connection.\n");
        return false;
    }

    /* Wait up to 5 seconds for the connection attempt to succeed. */
    if (enet_host_service (m_host, & event, 5000) <= 0 ||
        event.type != ENET_EVENT_TYPE_CONNECT)
    {
        /* Either the 5 seconds are up or a disconnect event was */
        /* received. Reset the peer in the event the 5 seconds   */
        /* had run out without any significant event.            */
        enet_peer_reset (peer);

        fprintf(stderr, "Connection to '%s:%d' failed.\n",
                hostName, portHost);
        return false;
    }
    m_server = peer;

    return true;
}  // initClient
Esempio n. 27
0
        ServerBase::ServerBase(const std::string &listenAddress, const Kiaro::Common::U16 &listenPort, const Kiaro::Common::U32 &maximumClientCount) : mIsRunning(true), mInternalHost(NULL),
        mListenPort(listenPort), mListenAddress(listenAddress)
        {
            ENetAddress enetAddress;
            enetAddress.port = listenPort;
            enet_address_set_host(&enetAddress, listenAddress.c_str());

            mInternalHost = enet_host_create(&enetAddress, maximumClientCount, 2, 0, 0);
            if (!mInternalHost)
            {
                mIsRunning = false;

                throw std::runtime_error("ServerBase: Failed to create ENet host!");
                   return;
            }
        }
Esempio n. 28
0
	CConexion* CClienteENet::connect(char* address, int port, int channels, unsigned int timeout)
	{
		if(estado = NO_INIT)
			return NULL;

		ENetAddress _address;
		ENetEvent event;
		CConexionENet* conexion = 0;

		/* Connect */
		enet_address_set_host (& _address, address);
		_address.port = port;

		ENetPeer* peer = enet_host_connect (client, & _address, channels);    
	    
		if (peer == NULL)
		{
			printf ("No available peers for initiating an ENet connection.\n");
		}
		else
		{
			/* Wait up to 5 seconds for the connection attempt to succeed.*/
			if (enet_host_service (client, & event, timeout*1000) > 0 &&
				event.type == ENET_EVENT_TYPE_CONNECT)
			{		
				if(DEBUG_CLIENT)
					fprintf(stdout, "Connection succeeded.");
				conexion = new CConexionENet();
				conexion -> setENetPeer(peer);
				listaConexiones.push_back(conexion);
			}
			else
			{
				/* Either the 5 seconds are up or a disconnect event was */
				/* received. Reset the peer in the event the 5 seconds   */
				/* had run out without any significant event.            */
				enet_peer_reset (peer);

				printf ("Connection  failed.");
			}
		}

	    enet_host_flush (client);
		estado = INIT_AND_CONNECTED;

		return conexion;
	}
Esempio n. 29
0
    void Client::connect()
    {
        ENetAddress address;
        ENetEvent event;
        m_connected = true;
        enet_address_set_host(&address, m_serverAdress.c_str());
        address.port = m_serverPort;

        LOG(INFO) << "Trying to connect to " << m_serverAdress << ":" << m_serverPort << ".";

        m_serverPeer = enet_host_connect(m_client, &address, 2, 0);
        if(m_serverPeer == nullptr)
        {
            LOG(FATAL) << "No available peers to initialize connection!";
            m_connected = false;
        }
    }
Esempio n. 30
0
bool connection_join(const char *hostname, uint16_t port) {
    destroy_host();

    ENetAddress address;
    enet_address_set_host(&address, hostname);
    address.port = port;

    host = enet_host_create(NULL, 1, CHANNEL_COUNT, 0, 0);
    server = enet_host_connect(host, &address, CHANNEL_COUNT, 0);

    ENetEvent event;
    if (enet_host_service(host, &event, 1000) > 0 && event.type == ENET_EVENT_TYPE_CONNECT) {
        entity_reset_all();
    }

    return host != NULL;
}