示例#1
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
    }
示例#2
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;
            }
        }
    }
示例#3
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;
}
示例#4
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);
}
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 ;
	}
}
示例#6
0
/* The core API functions for a connection: 
  renet_connection_connect
  renet_connection_disconnect
  renet_connection_send_packet
  renet_connection_send_queued_packets
  renet_connection_update
  renet_connection_use_compression
  renet_connection_online
*/
VALUE renet_connection_connect(VALUE self, VALUE timeout)
{
  Connection* connection;
  Data_Get_Struct(self, Connection, connection);
  VALUE lock = rb_iv_get(self, "@lock");
  rb_mutex_lock(lock);

  VALUE rv = Qfalse;

  if (connection->online == 0)
  {
    connection->peer = enet_host_connect(connection->host, connection->address, connection->channels, 0);    
      
    if (connection->peer == NULL)
    {
      rb_raise(rb_eStandardError, "Cannot connect to remote host");
    }
    
    if (service(self, connection, NUM2UINT(timeout)) > 0 && connection->event->type == ENET_EVENT_TYPE_CONNECT)
    {
      connection->online = 1;
      renet_connection_execute_on_connection(self);
      rv = Qtrue;
    }
    else
    {
      enet_peer_reset(connection->peer);
    }
  }

  rb_mutex_unlock(lock);
  return rv;
}
示例#7
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() ) );
    }
}
示例#8
0
文件: network.cpp 项目: foxblock/Pong
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;
	}
}
示例#9
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);
		}
	}
}
示例#10
0
文件: enet_lua.c 项目: JoJo2nd/Heart
int enet_lua_api enet_lua_host_connect(lua_State* L) {
    ENetHost** udata = luaL_checkudata(L, 1, "_enet.host");
    enet_lua_Address_t* address = luaL_checkudata(L, 2, "_enet.address");
    enet_uint32 channels = luaL_checkint(L, 3);
    enet_host_connect(*udata, &address->address_, channels, 0);
    return 0;
}
示例#11
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);
}
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;
}
示例#13
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;
}
示例#14
0
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;
}
void EnetClient::Connect(void)
{
    std::cout << "before enet_host_connect" << std::endl;
    /* Initiate the connection, allocating the two channels 0 and 1. */
    ENetPeer* peer = enet_host_connect(client_ptr_.get(), &server_addr_, 2, 0);    
    if (peer == NULL)
    {
        fprintf (stderr, "No available peers for initiating an ENet connection.\n");
        exit (EXIT_FAILURE);
    }
    peer_ptr_.reset(peer, enet_peer_reset);

    /* Wait up to 5 seconds for the connection attempt to succeed. */
    ENetEvent event;
    if (enet_host_service(client_ptr_.get(), &event, 5000) > 0 &&
            event.type == ENET_EVENT_TYPE_CONNECT)
    {
        puts ("Connection to some.server.net:1234 succeeded.");
    }
    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.            */
        peer_ptr_.reset();
        puts ("Connection to some.server.net:1234 failed.");
    }
}
示例#16
0
int NetworkManager::connexionToHost(std::string url,int port)
{
	/* Connect to some.server.net:1234. */
	    enet_address_set_host (& address,url.c_str());
	    address.port = port;

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

	    if (peer == NULL)
	    {
	       return 1;
	    }

	    /* Wait up to 5 seconds for the connection attempt to succeed. */
	    if (enet_host_service (client, &eventClient, 5000) > 0 && eventClient.type == ENET_EVENT_TYPE_CONNECT)
	    {
	    	isConnectedflag = true;
            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 ;
	    }
}
示例#17
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;
}
示例#18
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;
		}
示例#19
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);

	}
}
示例#20
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);
}
示例#21
0
/**
	Connect out from a server socket.
	Returns an ENetPeer *, which has not yet connected, or throws if connection fails.
**/
static value udpr_connect_out(value h, value ip, value port, value channels, value timeout) {
    ENetAddress address;
    ENetEvent event;
    ENetHost *host;
    ENetPeer *peer;
    int to;

	val_check_kind(h,k_udprhost);

	// checked in address population
	//val_check(ip,int);
	//val_check(port,int);
	val_check(channels,int);
	val_check(timeout,int);
	to = val_int(timeout);
	if(to < 0)
		to = 5000;

	host = (ENetHost *)val_data(h);
	if(populate_address(&address, ip, port) != val_true)
		val_throw(alloc_string("address"));
		//neko_error();

    // Initiate the connection with channels 0..channels-1
    peer = enet_host_connect (host, &address, (size_t)val_int(channels));
    if (peer == NULL)
    	//val_throw( alloc_string("Host not found") );
    	neko_error();

 	value v = alloc_abstract(k_udprpeer,peer);
	return v;
}
示例#22
0
bool HostClient::connect( const HostConnectionDetails& details )
{
    if( state != HostState::Disconnected )
        return false;

    state = HostState::Connecting;

    host = CreateEnetSocket(nullptr);

    if( !host )
        return false;

    ENetAddress addr;
    addr.host = 0;
    addr.port = details.port;

    enet_address_set_host( &addr, details.address.c_str() );

    size_t channelCount = 2;
    enet_uint32 data = 0;

    ENetPeer* newPeer = enet_host_connect(host, &addr, channelCount, data);

    peer = Allocate(gs_NetworkAllocator, Peer);
    peer->peer = newPeer;

    return true;
}
示例#23
0
文件: network.cpp 项目: voidah/tak
NetworkPeer Network::Connect(const std::string& host, unsigned short port, NetworkCallback* callback)
{
    AutoLock<Mutex> lock(m_mutex);

    if(!m_host)
        return NetworkPeer(0);

    if(m_type != CLIENT)
    {
        std::cout << "Connect operation valid only if type is client" << std::endl;
        return NetworkPeer(0);
    }

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

    ENetPeer* peer = enet_host_connect((ENetHost*)m_host, &address, NETWORK_CHANNEL_COUNT, 0);    

    if(!peer)
    {
        std::cout << "Failed to connect to " << host << ":" << port << std::endl;
        return NetworkPeer(0);
    }

    m_networkCallback = callback;

    ENetEvent event;
    if(enet_host_service((ENetHost*)m_host, &event, 5000) > 0 && event.type == ENET_EVENT_TYPE_CONNECT)
        return NetworkPeer(peer);

    enet_peer_reset(peer);
    std::cout << "Failed to connect to " << host << ":" << port << std::endl;
    return NetworkPeer(0);
}
示例#24
0
 bool Client::connect_to_server()
 {
     _F_reset_connection();
     _V_client_connection=enet_host_connect(_V_client_host,&_V_address,2,0);
     if(!_V_client_connection)
         return false;
     return (_V_status_connected=_F_test_connection());
 }
示例#25
0
// called from ---NETPLAY--- thread
void NetPlayClient::OnConnectReady(ENetAddress addr)
{
	if (m_state == WaitingForTraversalClientConnectReady)
	{
		m_state = Connecting;
		enet_host_connect(m_client, &addr, 0, 0);
	}
}
示例#26
0
文件: main.c 项目: 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;
}
示例#27
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;
}
示例#28
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;
}
示例#29
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;
    }
}
	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);
        }
	}