Example #1
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;
}
Example #2
0
	ServerBase::ServerBase( int port, int maxClients, int numChannels, int incomingBytes /*= 0*/, int outgoingBytes /*= 0*/)
		: m_server(NULL), m_listener(NULL)
	{
		m_keyMsg = "nZGlA5C7pBWTpVCh8xC7Ad";

		m_address.port = port;
		if(port != 0)
		{
			m_address.host = ENET_HOST_ANY;

			m_server = enet_host_create(
				&m_address,maxClients,numChannels,incomingBytes,outgoingBytes);

			if(m_server == NULL)
			{
				throw Exception("Server Host failed to be created!");
			}

		}
		else
		{
			m_server = enet_host_create(
				NULL,1,numChannels,incomingBytes,outgoingBytes);
			if(m_server == NULL)
			{
				throw Exception("Server Client failed to be created!");
			}
		}

	
	}
Example #3
0
bool ConnectionHandler::startListen(enet_uint16 port,
                                    const std::string &listenHost)
{
    // Bind the server to the default localhost.
    address.host = ENET_HOST_ANY;
    address.port = port;

    if (!listenHost.empty())
        enet_address_set_host(&address, listenHost.c_str());

    LOG_INFO("Listening on port " << port << "...");
#if defined(ENET_VERSION) && ENET_VERSION >= ENET_CUTOFF
    host = enet_host_create(
            &address    /* the address to bind the server host to */,
            Configuration::getValue("net_maxClients", 1000) /* allowed connections */,
            0           /* unlimited channel count */,
            0           /* assume any amount of incoming bandwidth */,
            0           /* assume any amount of outgoing bandwidth */);
#else
    host = enet_host_create(
            &address    /* the address to bind the server host to */,
            Configuration::getValue("net_maxClients", 1000) /* allowed connections */,
            0           /* assume any amount of incoming bandwidth */,
            0           /* assume any amount of outgoing bandwidth */);
#endif

    return host != 0;
}
Example #4
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;
            }
        }
    }
Example #5
0
Error GDNetHost::bind(Ref<GDNetAddress> addr) {
	ERR_FAIL_COND_V(_host != NULL, FAILED);

	if (addr.is_null()) {
		_host = enet_host_create(NULL, _max_peers, _max_channels, _max_bandwidth_in, _max_bandwidth_out);
	} else {
		CharString host_addr = addr->get_host().ascii();

		ENetAddress enet_addr;
		enet_addr.port = addr->get_port();

		if (host_addr.length() == 0) {
			enet_addr.host = ENET_HOST_ANY;
		} else {
			if (enet_address_set_host(&enet_addr, host_addr.get_data()) != 0) {
				ERR_EXPLAIN("Unable to resolve host");
				return FAILED;
			}
		}

		_host = enet_host_create(&enet_addr, _max_peers, _max_channels, _max_bandwidth_in, _max_bandwidth_out);
	}

	ERR_FAIL_COND_V(_host == NULL, FAILED);

	thread_start();

	return OK;
}
Example #6
0
void
shmup_game_network_connect(shmup_game *g, int network_type, char *hostname)
{
	ENetEvent event;
	ENetAddress address;
	
	g->network_type = network_type;
	if (g->network_type == SERVER) {		
		address.host = ENET_HOST_ANY;
		address.port = 4000;		
		fprintf(stderr, "initializing server on port %d...\n", address.port);
		g->host = enet_host_create(&address, 4, 2, 0, 0);		
	} else {		
		fprintf(stderr, "initializing client...\n");
		enet_address_set_host(&address, hostname);
		address.port = 4000;
		g->host = enet_host_create(NULL, 1, 2, 0, 0);
		g->peer = enet_host_connect(g->host, &address, 2, 0);		
		if (g->peer == NULL) {
			fprintf (stderr, "No available peers for initiating an ENet connection.\n");
			exit (EXIT_FAILURE);
		}		
		if (enet_host_service (g->host, &event, 5000) > 0 &&
		    event.type == ENET_EVENT_TYPE_CONNECT) {
			printf("Connection to %s:4000 succeeded.\n", hostname);
			g->player[g->num_players].pos = v2(g->window_width/2, g->window_height/2);
			g->player[g->num_players].vel = v2zero;
			g->player[g->num_players].acc = v2zero;
			g->num_players++;
		} else {
			enet_peer_reset(g->peer);
			printf("Connection to %s:4000 failed.\n", hostname);
		}
	}
}
Example #7
0
shmup_game *
shmup_game_init()
{
	ENetAddress e;
	shmup_game *g;
	
	g = malloc(sizeof(shmup_game));
	glfwGetWindowSize(&g->window_width, &g->window_height);
	
	g->render_type = 2;
	g->quit = 0;	
	g->emitter = v2(g->window_width / 2, g->window_height / 2);
	g->gravity = v2(0, -250);	
	g->bpool = bpool_new(8000);	
	
	g->bpool->tex[0] = SOIL_load_OGL_texture("./data/flare.tga",
						 SOIL_LOAD_AUTO,
						 SOIL_CREATE_NEW_ID, 0);	
	if(g->bpool->tex[0] == 0)
		fprintf(stderr, "loading error: '%s'\n", SOIL_last_result());
	
	g->bpool->tex[1] = SOIL_load_OGL_texture("./data/arrow.tga",
						 SOIL_LOAD_AUTO,
						 SOIL_CREATE_NEW_ID, 0);
	if(g->bpool->tex[1] == 0)
		fprintf(stderr, "loading error: '%s'\n", SOIL_last_result());	
	
	g->bpool->prog = load_shaders("./data/glsl/bullets.vsh", 
				      "./data/glsl/bullets.fsh");
	
	if (enet_initialize () != 0) {
		fprintf (stderr, "An error occurred while initializing ENet.\n");
		exit(EXIT_FAILURE);
	}
	
	if (g->network_type == SERVER) {
		e.host = ENET_HOST_ANY;
		e.port = 4000;
		g->host = enet_host_create(&e, 4, 2, 0, 0);
	} else {
		g->host = enet_host_create(NULL, 4, 2, 0, 0);
	}
	
	g->player[0].pos = v2(g->window_width/2, g->window_height/2);
	g->player[0].vel = v2zero;
	g->player[0].acc = v2zero;
	
//	fire(g, 1000, 0);
//	fire(g, 1000, 1);
	
	return g;
}
Example #8
0
    Host::Host():
        mServer(NULL), mConnected(false)
    {
        // create a new client host for connecting to the server
#ifdef ENET_VERSION
        mClient = enet_host_create(NULL, 1, 0, 57600 / 8, 14400 / 8);
#else
        mClient = enet_host_create (NULL /* create a client host */,
                1 /* only allow 1 outgoing connection */,
                57600 / 8 /* 56K modem with 56 Kbps downstream bandwidth */,
                14400 / 8 /* 56K modem with 14 Kbps upstream bandwidth */);
#endif
    }
Example #9
0
bool Room::Create(const std::string& name, const std::string& server_address, u16 server_port,
                  const std::string& password, const u32 max_connections,
                  const std::string& preferred_game, u64 preferred_game_id) {
    ENetAddress address;
    address.host = ENET_HOST_ANY;
    if (!server_address.empty()) {
        enet_address_set_host(&address, server_address.c_str());
    }
    address.port = server_port;

    room_impl->server = enet_host_create(&address, max_connections, NumChannels, 0, 0);
    if (!room_impl->server) {
        return false;
    }
    room_impl->state = State::Open;

    room_impl->room_information.name = name;
    room_impl->room_information.member_slots = max_connections;
    room_impl->room_information.port = server_port;
    room_impl->room_information.preferred_game = preferred_game;
    room_impl->room_information.preferred_game_id = preferred_game_id;
    room_impl->password = password;
    room_impl->CreateUniqueID();

    room_impl->StartLoop();
    return true;
}
Example #10
0
Server::Server(uint16 port, const char *worldId) {
	save = std::unique_ptr<Save>(new Save(worldId));
	boost::filesystem::path path(save->getPath());
	if (!boost::filesystem::exists(path)) {
		boost::filesystem::create_directories(path);
		std::random_device rng;
		boost::random::uniform_int_distribution<uint64> distr;
		uint64 seed = distr(rng);
		save->initialize(worldId, seed);
		save->store();
	}

	ServerChunkManager *cm = new ServerChunkManager(save->getWorldGenerator(), save->getChunkArchive());
	chunkManager = std::unique_ptr<ServerChunkManager>(cm);
	world = std::unique_ptr<World>(new World(chunkManager.get()));

	LOG_INFO(logger) << "Creating server";

	gameServer = std::unique_ptr<GameServer>(new GameServer(this));
	chunkServer = std::unique_ptr<ChunkServer>(new ChunkServer(this));

	if (enet_initialize() != 0)
		LOG_FATAL(logger) << "An error occurred while initializing ENet.";

	ENetAddress address;
	address.host = ENET_HOST_ANY;
	address.port = port;
	host = enet_host_create(&address, MAX_CLIENTS, NUM_CHANNELS, 0, 0);
	if (!host)
		LOG_FATAL(logger) << "An error occurred while trying to create an ENet server host.";
}
Example #11
0
void Network::InitializeClient(const char* ipAdress, const short port, const unsigned int maxDownstream, const unsigned int maxUpstream)
{
	std::cout << "Initializing client at port " << port << ".\n";

	_host = enet_host_create (NULL, 1, 2, maxDownstream, maxUpstream);

	if (_host == NULL)
		std::cout << "An error occurred while trying to create an ENet client host.\n";
	else
		std::cout << "Succesfully created ENet client host.\n";

	enet_address_set_host(&_address, ipAdress);
	_address.port = port;

	_peer = enet_host_connect(_host, &_address, 2, 0);

	if (_peer == NULL)
		std::cout << "No available peers for initiating an ENet connection.\n";

	// If connect send packages
	if (enet_host_service(_host, &_event, 1500) > 0 && _event.type == ENET_EVENT_TYPE_CONNECT)
	{
		_isConnected = true;
		printf("Connection to %s:%i succeeded.\n", ipAdress, _address.port);
		StartThreads();	
	}
	else
	{
		enet_peer_reset(_peer);
		printf("Connection to %s:%i failed.\n", ipAdress, _address.port);

	}
}
Example #12
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;
}
Example #13
0
void Client::Connect(std::string ip, int port)
{
    client = enet_host_create(NULL, 1, 2, 57600, 14400);
    if(client == NULL) {
        std::cout << "Cannot create client." << std::endl;
    }
}
Example #14
0
bool EnsureTraversalClient(const std::string& server, u16 server_port, u16 listen_port)
{
  if (!g_MainNetHost || !g_TraversalClient || server != g_OldServer ||
      server_port != g_OldServerPort || listen_port != g_OldListenPort)
  {
    g_OldServer = server;
    g_OldServerPort = server_port;
    g_OldListenPort = listen_port;

    ENetAddress addr = {ENET_HOST_ANY, listen_port};
    ENetHost* host = enet_host_create(&addr,  // address
                                      50,     // peerCount
                                      1,      // channelLimit
                                      0,      // incomingBandwidth
                                      0);     // outgoingBandwidth
    if (!host)
    {
      g_MainNetHost.reset();
      return false;
    }
    g_MainNetHost.reset(host);
    g_TraversalClient.reset(new TraversalClient(g_MainNetHost.get(), server, server_port));
  }
  return true;
}
Example #15
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;
}
Example #16
0
void ServerSystem::Init()
{
    if ( enet_initialize () != 0 )
    {
        L1 ( "An error occurred while initializing ENet.\n" );
    }
    atexit ( enet_deinitialize );
    mOnFrameCounterEvent = EventServer<engine::FrameCounterEvent>::Get().Subscribe( boost::bind( &ServerSystem::OnFrameCounterEvent, this, _1 ) );
    mOnClientIdChanged = EventServer<ClientIdChangedEvent>::Get().Subscribe( boost::bind( &ServerSystem::OnClientIdChanged, this, _1 ) );

    /* Bind the server to the default localhost.     */
    /* A specific host address can be specified by   */
    /* enet_address_set_host (& address, "x.x.x.x"); */
    mAddress.host = ENET_HOST_ANY;
    /* Bind the server to port 1234. */
    mAddress.port = 1234;
    mServer = enet_host_create ( & mAddress /* the address to bind the server host to */,
                                 32      /* allow up to 32 clients and/or outgoing connections */,
                                 2      /* allow up to 2 channels to be used, 0 and 1 */,
                                 0      /* assume any amount of incoming bandwidth */,
                                 0      /* assume any amount of outgoing bandwidth */ );
    if ( mServer == NULL )
    {
        L1 ( "An error occurred while trying to create an ENet server host.\n" );
    }
}
Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int p_in_bandwidth, int p_out_bandwidth){

	ERR_FAIL_COND_V(active,ERR_ALREADY_IN_USE);

	ENetAddress address;
	address.host = bind_ip;

	address.port = p_port;

	host = enet_host_create (& address /* the address to bind the server host to */,
				     p_max_clients      /* allow up to 32 clients and/or outgoing connections */,
				     2      /* allow up to 2 channels to be used, 0 and 1 */,
				     p_in_bandwidth      /* assume any amount of incoming bandwidth */,
				     p_out_bandwidth      /* assume any amount of outgoing bandwidth */);

	ERR_FAIL_COND_V(!host,ERR_CANT_CREATE);

	_setup_compressor();
	active=true;
	server=true;
	refuse_connections=false;
	unique_id=1;
	connection_status=CONNECTION_CONNECTED;
	return OK;
}
    bool GEINetworkServerHost::setServerHost(std::string address, unsigned short netPort,
            size_t peerCount,
            size_t channelLimit,
            int incomingBandwidth,
            int outgoingBandwidth)
    {

        ENetAddress enetAddress;
        if (!address.empty())
        {
            enet_address_set_host (& enetAddress, address.c_str());

            enetAddress.port = netPort;
        }
        else
        {
            enetAddress.host = ENET_HOST_ANY;
            enetAddress.port = netPort;
        }

        enetServerHost = enet_host_create (& enetAddress /* the address to bind the server host to */,
                                 peerCount      /* allow up to 32 clients and/or outgoing connections */,
                                 channelLimit /* allow up to 2 channels to be used, 0 and 1 */,
                                 incomingBandwidth     /* assume any amount of incoming bandwidth */,
                                 outgoingBandwidth /* assume any amount of outgoing bandwidth */);

        if (enetServerHost == NULL)
        {
            fprintf (stderr,
                     "An error occurred while trying to create an ENet server host.\n");
            return false;
        }
        return true;
    }
Example #19
0
UdpSocket * UdpSocket::CreateServer(std::string localHost, int localPort, int maxConnections)
{
    UdpSocket *socket = new UdpSocket();

    // Create ENetHost
    ENetAddress address;
    if ( localHost == "" )
    {
        address.host = ENET_HOST_ANY;
    }
    else
    {
        // TODO
        throw 5;
    }
    address.port = localPort;

    socket->host = enet_host_create(&address, maxConnections, 0, 0);
    if ( !socket->host )
    {
        throw 5; // TODO: Use ri7::core::Exception
    }

    return socket;
}
Example #20
0
int main (int argc, char * const argv[]) {
    
    if(enet_initialize() != 0)
	{
		printf("An error occurred while initializing ENet.\n");
	}
	
	ENetAddress address;
	ENetHost* server;
	
	address.host = ENET_HOST_ANY;
	address.port = 9050;
	
	// up to 32 clients with unlimited bandwidth
	server = enet_host_create(&address, 32, 0, 0);
	if(server == NULL)
	{
		printf("An error occurred while trying to create an ENet server host.\n");
	}
	
	int clients = 0;
	
	// server main loop
	while(true)
	{
		ENetEvent event;
		while(enet_host_service(server, &event, 1000) > 0)
		{
			switch(event.type)
			{
				case ENET_EVENT_TYPE_CONNECT:
					printf ("A new client connected from %x:%u.\n", 
							event.peer -> address.host,
							event.peer -> address.port);
					
					clients++;
					
					break;
					
				case ENET_EVENT_TYPE_RECEIVE:
					printf ("A packet of length %u containing %s was received.\n",
							event.packet->dataLength,
							event.packet->data);
					
					ENetPacket* packet = enet_packet_create(event.packet->data, event.packet->dataLength, ENET_PACKET_FLAG_RELIABLE);
					enet_host_broadcast(server, 0, packet);
					enet_host_flush(server);
					
					enet_packet_destroy(event.packet);
					break;
					
				case ENET_EVENT_TYPE_DISCONNECT:
					printf("Client disconnected.\n");
					event.peer->data = NULL;
			}
		}
	}
	
	return 0;
}
Example #21
0
bool Network::Init(NETWORK_TYPE networkType)
{
    AutoLock<Mutex> lock(m_mutex);

    if(networkType == NONE)
        return false;

    if(enet_initialize() != 0)
    {
        std::cout << "Error initializing network" << std::endl;
        return false;
    }

    if(networkType == CLIENT)
    {
        m_host = enet_host_create (NULL, 1, NETWORK_CHANNEL_COUNT, 0, 0);

        if(!m_host)
        {
            std::cout << "Error initializing connection" << std::endl;
            return false;
        }
    }

    m_type = networkType;
    return true;
}
Example #22
0
	bool CClienteENet::init(unsigned int maxConnections, unsigned int maxinbw, unsigned int maxoutbw)
	{
		if(estado != NO_INIT)
			return false;

		if (enet_initialize () != 0)
		{
			printf ("An error occurred while initializing ENet.\n");
			return false;

		}

		client = enet_host_create (NULL /* create a client host */,
                maxConnections, /* only allow 1 outgoing connection */
                maxinbw ,
                maxoutbw );

		if (client == NULL)
		{
			printf ("An error occurred while trying to create an ENet client host.\n");
			return false;
		}
		if(DEBUG_CLIENT)
			fprintf(stdout, "Client initialized");
	
		estado = INIT_NOT_CONNECTED;

		return true;
	}
Example #23
0
int joynet_connect_client_to_server(JOYNET_CLIENT * cp, char * host, int port)
{
	ENetEvent event;
	
	if(enet_address_set_host(&cp->address, host) < 0)
	{
		return 0;
	}
	cp->address.port = port;
	cp->host = enet_host_create(NULL, 1, 0, 0, 0);
	if(!cp->host)
	{
		return 0;
	}
	cp->peer = enet_host_connect(cp->host, &cp->address, 4, 0);
	if(!cp->peer)
	{
		return 0;
	}
	if(enet_host_service(cp->host, &event, 5000) > 0 && event.type == ENET_EVENT_TYPE_CONNECT)
    {
		return 1;
    }
    else
    {
        enet_peer_reset(cp->peer);
    }
	return 0;
}
Example #24
0
void network_init()
{
  ENetAddress address;
  int status, port, max_clients;
  gchar *server;

  network = g_malloc(sizeof(*network));

  server = (gchar *) config_get_string("server", default_server);
  port = config_get_int("port", default_port);
  max_clients = config_get_int("max_clients", default_max_clients);

  status = enet_initialize();
  g_return_if_fail(status == 0);

  enet_address_set_host(&address, server);
  address.port = port;

  network->server = enet_host_create(&address, max_clients, 
#ifdef HAS_RECENT_ENET
                                     2, 
#endif
                                     0, 0);
  g_return_if_fail(network->server != NULL);
  g_debug("Listening on %s:%d", server, port);

  network->clients = NULL;
  g_free(server);
}
Error NetworkedMultiplayerENet::create_client(const IP_Address& p_ip,int p_port, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth){

	ERR_FAIL_COND_V(active,ERR_ALREADY_IN_USE);

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

	ERR_FAIL_COND_V(!host,ERR_CANT_CREATE);


	ENetAddress address;
	address.host=p_ip.host;
	address.port=p_port;

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

	if (peer == NULL) {
		enet_host_destroy(host);
		ERR_FAIL_COND_V(!peer,ERR_CANT_CREATE);
	}

	//technically safe to ignore the peer or anything else.

	connection_status=CONNECTION_CONNECTING;
	active=true;
	server=false;

	return OK;
}
Example #26
0
void ClientSystem::Connect()
{
    if ( mProgramState.mClientConnected )
    {
        L1( "Already connected, won't try it again!\n" );
        return; //Really wont try again
    }
    //        ENetAddress address2;
    //         address2.host = ENET_HOST_ANY;
    //         /* Bind the server to port 1234. */
    //         address2.port = 1236;
    mClient = 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 */,
                                 0 ,
                                 0 );
    if ( mClient == NULL )
    {
        L1( "An error occurred while trying to create an ENet client host.\n" );
        exit ( EXIT_FAILURE );
    }

    ENetAddress address;
    ENetEvent event;
    /* Connect to some.server.net:1234. */
    address.port = 1234;
    enet_address_set_host ( & address, core::ProgramState::Get().mServerIp.c_str() ); //core::ProgramState::Get().mServerIp.c_str());
    /* Initiate the connection, allocating the two channels 0 and 1. */
    mPeer = enet_host_connect ( mClient, & address, 2, 0 );
    if ( mPeer == NULL )
    {
        L1( "No available peers for initiating an ENet connection.\n" );
        exit ( EXIT_FAILURE );
    }
    bool connectSuccess = false;
    for( size_t i = 0; i < 500; ++i )
    {
        if ( enet_host_service ( mClient, & event, 10 ) > 0 &&
             event.type == ENET_EVENT_TYPE_CONNECT )
        {
            connectSuccess = true;
            break;
        }
    }
    enet_host_flush( mClient );
    if( !connectSuccess )
    {
        L1( "Connection timed out.\n" );
        enet_peer_reset ( mPeer );
        engine::Engine::Get().GetSystem<engine::WindowSystem>()->Close();
    }
    else
    {
        mProgramState.mClientConnected = true;
        std::auto_ptr<MyNameMessage> msg( new MyNameMessage );
        msg->mName = core::ProgramState::Get().mClientName;
        msg->mControlledLocalPlayerId = 1; // TODO: change when multiple local players are allowed
        mMessageHolder.AddOutgoingMessage( std::auto_ptr<Message>( msg.release() ) );
    }
}
Example #27
0
void NetworkHelper::StartServer(unsigned short port)
{
	if (connectionType != ConnectionType::Server)
	{
		return;
	}

	ENetAddress address;
	address.host = ENET_HOST_ANY;
	address.port = port;
	host = enet_host_create(&address, 32, 2, 0, 0);

	if (host == NULL)
	{
		Logger::LogErrorf("Unable to create a host on port %d", port);
	}
	else
	{
		Logger::Log("Server started\n");
	}

	if (automaticPortMapping) {
		portMapping.Create(port);
	}
}
Example #28
0
		bool Manager::createClient(const std::string &host, sf::Uint16 port)
		{
			_host = enet_host_create(
				NULL, // client host
				1, // one outgoing connection
				1, // one channel
				0, // automatic downstream bandwidth
				0 // automatic upstream bandwidth
				);
			if (_host == nullptr)
			{
				std::cerr << "An error occurred while trying to create an ENet client host." << std::endl;
				return false;
			}

			ENetAddress address;
			enet_address_set_host(&address, host.c_str());
			address.port = port;

			_server = enet_host_connect(_host, &address, 2, 0);
			if (_server == nullptr)
			{
				std::cerr << "No available peers for initiating an ENet connection." << std::endl;
				return false;
			}

			std::cout << "Connecting to host " << host << " on port " << port << "." << std::endl;
			return true;
		}
Example #29
0
Network::Network( std::string Server, int Port )
{
	localHost = enet_host_create (NULL /* create a client host */,
		1 /* only allow 1 outgoing connection */,
		1 /* 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 */);
		0 /* assume any amount of incoming bandwidth */,
		0 /* assume any amount of outgoing bandwidth */);
	if( localHost == 0 )
	{
		return;
	}
	enet_address_set_host( &serverAddress, Server.c_str() );
	serverAddress.port = Port;
	networkPeer = enet_host_connect( localHost, &serverAddress, 1, 0 );
	if( networkPeer == 0 )
	{
		enet_host_destroy( localHost );
		localHost = 0;
		return;
	}

	/* Wait up to 6 seconds for the connection attempt to succeed. */
	ENetEvent ev;
	if( enet_host_service( localHost, &ev, 6000 ) > 0 && ev.type == ENET_EVENT_TYPE_CONNECT )
	{
	} else {
		enet_peer_reset( networkPeer );
		networkPeer = 0;
		enet_host_destroy( localHost );
		localHost = 0;
		return;
	}
}
Example #30
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);

  ENetAddress address;
  address.host = ENET_HOST_ANY;
  address.port = SOCKK;
  printf("create!\n");
  host = enet_host_create (& address /* the address to bind the server host to */,
                             32 /* allow up to 32 clients and/or outgoing connections */,
                             2 /* allow up to 2 channels to be used, 0 and 1 */,
                             0 /* assume any amount of incoming bandwidth */,
                             0 /* assume any amount of outgoing bandwidth */);
  if (host == NULL)
  {
    fprintf (stderr,
    "An error occurred while trying to create an ENet server host.\n");
    exit (EXIT_FAILURE);
  }

#if EMSCRIPTEN
  emscripten_set_main_loop(main_loop, 3, 1);
#else
  while (1) main_loop();
#endif

  return 1;
}