Example #1
0
void NetworkManager::NetworkClient(char* str)    //http://content.gpwiki.org/index.php/SDL:Tutorial:Using_SDL_net <- good code here, adapt messages accordingly
{                           //http://jcatki.no-ip.org:8080/SDL_net/SDL_net.html <- good documentation here
	IPaddress ip;           /* Call this function once client is selected (after accepting a host if that is possible via GUI) */         
	int len;
	char buffer[512];
	server = false;
	host=str;							//If a GUI - entered host name is possible, add it to the function arguments and set this to it.
	if (SDLNet_Init() < 0)
	{
		fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
 
	/* Resolve the host we are connecting to */
	if (SDLNet_ResolveHost(&ip, host, 2000) < 0)
	{
		fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
 
	/* Open a connection with the IP provided (listen on the host's port) */
	if (!(targetSocket = SDLNet_TCP_Open(&ip)))
	{
		fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
 
}
/**************************************
 * CLIENT
 *************************************/
int BomberNetClient::connectClient(SDL_Surface * vout_buf) {
	errorCode = 0;
	IPaddress serverIP;

	fprintf(stderr, "%s\n", GameConfig::Instance().getIpString());
	viewer = new ClientViewer(vout_buf);
	startKeystateThread();
	SDLNet_ResolveHost(&serverIP, GameConfig::Instance().getIpString(), GameConfig::Instance().getPortValue());

	if (serverIP.host == INADDR_NONE) {
		fprintf(stderr, "Couldn't resolve hostname\n");
		cleanup();
	} else {
		/* If we fail, it's okay, the GUI shows the problem */
		tcpsock = SDLNet_TCP_Open(&serverIP);
		if (tcpsock == NULL) {
			fprintf(stderr, "Connect failed\n");
			cleanup();
			return 1;
		} else {
			fprintf(stderr, "Connection established !\n");
			socketset = SDLNet_AllocSocketSet(1);
			SDLNet_TCP_AddSocket(socketset, tcpsock);
			alive = true;
			net_thread = SDL_CreateThread(net_thread_main, "tcp client thread", tcpsock);
			return 0;
		}
	}
	return 2;
}
Example #3
0
void NetworkManager::NetworkHost(void)      //http://content.gpwiki.org/index.php/SDL:Tutorial:Using_SDL_net <- good code here, adapt messages accordingly
{                           //http://jcatki.no-ip.org:8080/SDL_net/SDL_net.html <- good documentation here
  TCPsocket sd;      /* Call this function once Host button is selected */
  IPaddress ip;
  char buffer[512];
  server = true;
	if (SDLNet_Init() < 0)
	{
		fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
 
	/* Resolving the host using NULL make network interface to listen */
	if (SDLNet_ResolveHost(&ip, NULL, 2000) < 0)
	{
		fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
 
	/* Open a connection with the IP provided (listen on the host's port) */
	if (!(sd = SDLNet_TCP_Open(&ip)))
	{
		fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
 
	/* Wait for a connection*/
	while (!(targetSocket = SDLNet_TCP_Accept(sd)))
	{
		
	}
	std::cout<<"accepted client";
 
}
Example #4
0
bool Network::realConnect()
{
    IPaddress ipAddress;

    if (SDLNet_ResolveHost(&ipAddress, mServer.hostname.c_str(),
        mServer.port) == -1)
    {
        std::string errorMessage = _("Unable to resolve host \"") +
            mServer.hostname + "\"";
        setError(errorMessage);
        logger->log("SDLNet_ResolveHost: %s", errorMessage.c_str());
        return false;
    }

    mState = CONNECTING;

    mSocket = SDLNet_TCP_Open(&ipAddress);
    if (!mSocket)
    {
        logger->log("Error in SDLNet_TCP_Open(): %s", SDLNet_GetError());
        setError(SDLNet_GetError());
        return false;
    }

    logger->log("Network::Started session with %s:%i",
        ipToString(ipAddress.host), ipAddress.port);

    mState = CONNECTED;

    return true;
}
/*
================
Thread Functions
================
*/
static void TcpLoop(bool *abort, ConnectionListener *listener, 
					NewConnectionCallback cb)
{
	IPaddress ip;
	TCPsocket server_socket = 0;

	if (SDLNet_ResolveHost(&ip, NULL, TCP_SERVER_PORT) == -1) {
		string msg = (string)"SDLNet_ResolveHost() failed : " + SDLNet_GetError();
		Log::Error(msg);
		throw std::runtime_error(msg);
	}

	server_socket = SDLNet_TCP_Open(&ip);
	if (!server_socket) {
		string msg = (string)"SDLNet_TCP_OPEN() failed: " + SDLNet_GetError();
		Log::Error(msg);
		throw std::runtime_error(msg);
	}

	while (!(*abort)) {
		TCPsocket new_socket = SDLNet_TCP_Accept(server_socket);

		if (new_socket) {
			Log::Debug("New TCP connection!");
			(*listener.*cb)(new_socket);
		}
		
		// Sleep for 100 milliseconds
		std::this_thread::sleep_for(std::chrono::microseconds(100000));
	}
}
Example #6
0
TCPClientSocket::TCPClientSocket(const char* destination, Bit16u port) {
#ifdef NATIVESOCKETS
	nativetcpstruct=0;
#endif
	sendbuffer=0;
	isopen = false;
	if(!SDLNetInited) {
        if(SDLNet_Init()==-1) {
			LOG_MSG("SDLNet_Init failed: %s\n", SDLNet_GetError());
			return;
		}
		SDLNetInited = true;
	}	
	mysock=0;
	listensocketset=0;
	
	IPaddress openip;
	//Ancient versions of SDL_net had this as char*. People still appear to be using this one.
	if (!SDLNet_ResolveHost(&openip,const_cast<char*>(destination),port)) {
		listensocketset = SDLNet_AllocSocketSet(1);
		if(!listensocketset) return;
		mysock = SDLNet_TCP_Open(&openip);
		if(!mysock) return;
		SDLNet_TCP_AddSocket(listensocketset, mysock);
		isopen=true;
	}
}
Example #7
0
/*  Setup TCP Server, and wait for a single
 *  client to connect */
int setup_server(unsigned port) { 

#if !defined(PSP) && !defined(EMSCRIPTEN) && !defined(DREAMCAST) && !defined(THREE_DS)
    is_server = 1;

    log_message(LOG_INFO, "Starting server on port %u\n",port);

    //SDL_INIT(SDL_INIT_EVERYTHING); 
    SDLNet_Init();   

    IPaddress ip;
    SDLNet_ResolveHost(&ip, NULL, port);

    server = SDLNet_TCP_Open(&ip);

    log_message(LOG_INFO, "Waiting for client to connect\n");
    
    while (client == NULL) {
        client = SDLNet_TCP_Accept(server);
        SDL_Delay(1000);
    }
    const char * message = "Welcome to GB server";
    SDLNet_TCP_Send(client, message, strlen(message) + 1);
    log_message(LOG_INFO, "Client successfully connected\n");
    socketset = SDLNet_AllocSocketSet(1); 
    SDLNet_TCP_AddSocket(socketset, client);
    connection_up = 1;
    return 1;
#endif
    return 0;
}
Example #8
0
int net_http_get(char* out, int max, char* fmt, ...) {
  
  va_list args;
  va_start(args, fmt);
  vsnprintf(url_buffer, 500, fmt, args);
  va_end(args);
  
  int parts = sscanf(url_buffer, "http://%[^/]%s", host_buffer, path_buffer);
  
  if (parts != 2) {
    warning("Couldn't resolve parts of URL '%s'", url_buffer);
    return HTTP_ERR_URL;
  }
  
  IPaddress ip;
  if ( SDLNet_ResolveHost(&ip, host_buffer, 80) == -1) {
    warning("Couldn't Resolve Host: %s", SDLNet_GetError());
    return HTTP_ERR_HOST;
  }

  TCPsocket sock = SDLNet_TCP_Open(&ip);
  
  if(!sock) {
    warning("Couldn't open socket: %s", SDLNet_GetError());
    return HTTP_ERR_SOCKET;
  }
  
  char sockout[1024*4];
  snprintf(sockout,(1024*4-1),
    "GET %s HTTP/1.1\r\n"
    "Host: %s\r\n"
    "\r\n", path_buffer, host_buffer);
  
  int result = SDLNet_TCP_Send(sock, sockout, strlen(sockout));
  
  if (result < strlen(sockout)) {
    warning("Error sending http request: %s", SDLNet_GetError());
    return HTTP_ERR_DATA;
  }
  
  char line[1024];
  bool header = true;
  
  strcpy(out, "");
  
  while (SDLNet_TCP_RecvLine(sock, line, 1023)) {
    
    /* TODO: Check against max arg */
    
    if (header) {
      if (strcmp(line, "\r\n") == 0) { header = false; }
    } else {
      strcat(out, line);
    }
    
  }
  
  return HTTP_ERR_NONE;
  
}
Example #9
0
/* Setup TCP Client, and attempt to connect
 * to the server */
int setup_client(unsigned port) {

#if !defined(PSP) && !defined(EMSCRIPTEN) && !defined(DREAMCAST) && !defined(THREE_DS)
    is_client = 1;

    log_message(LOG_INFO, "Attempting to connect to server on port %u\n",port);
    //SDL_INIT(SDL_INIT_EVERYTHING); 
    SDLNet_Init();   

    IPaddress ip;
    //TODO, for now always connect to localhost, fix for any specified ip in
    //the future
    SDLNet_ResolveHost(&ip, "localhost", port);

    client =  SDLNet_TCP_Open(&ip);
    socketset = SDLNet_AllocSocketSet(1); 
    char buf[100];
    int i = SDLNet_TCP_Recv(client, buf, 100);
    for (int j = 0; j < i; j++) {
        printf("%c",buf[j]);
    }
    printf("\n");
    SDLNet_TCP_AddSocket(socketset, client);
    connection_up = 1;
    return 1;
#endif
    return 0;

}
Example #10
0
TCPServer::TCPServer(const string& port) {
  if (port.size()) {
    IPaddress addr;
    SDLNet_ResolveHost(&addr, nullptr, Address::ntohs(Address("", port).port));
    sd = SDLNet_TCP_Open(&addr);
  }
}
bool MainApp::onLoadWorld()
{
	m_pFontTexture = peon::EngineCore::getSingleton().getRenderer()->loadTexture("data\\textures\\font.png");
	
	m_pFont = peon::EngineCore::getSingleton().getRenderer()->loadFont(16, 16, 14);

	SDLNet_Init();

	m_port = 9090;

	// Resolve the argument into an IPaddress type
	if(SDLNet_ResolveHost(&m_hostAddress,NULL,m_port)==-1)
	{
		return false;
	}

	// open the server socket
	m_hostSocket = SDLNet_TCP_Open(&m_hostAddress);
	if(!m_hostSocket)
	{
		//printf("SDLNet_TCP_Open: %s\n",SDLNet_GetError());
		//exit(4);
		return false;
	}

	
	return true;
}
Example #12
0
// ---------------------------------------------------------
bool CIncomingConnectionListener::start(ushort localPort, ushort maxConnections)
{
	m_listeningSocketSet = CSockSetPtr(new CSocketSet(1)); 
	if( m_listeningSocketSet->errorHasOccured() )
	{
		CLog::instance()->log(CLog::msgFlagNetwork, CLog::msgLvlCritical,_("Error allocating listening socket set.\n"));
		return false;
	};

	m_dataSocketSet = CSockSetPtr(new CSocketSet(maxConnections)); 
	if( m_dataSocketSet->errorHasOccured() )
	{
		CLog::instance()->log(CLog::msgFlagNetwork, CLog::msgLvlCritical,_("Error allocating data socket set.\n"));
		return false;
	};

	IPaddress addr;
	SDLNet_ResolveHost(&addr, NULL, localPort);
	m_listeningSocket = SDLNet_TCP_Open(&addr);
	if ( m_listeningSocket == NULL )
	{
		CLog::instance()->log(CLog::msgFlagNetwork, CLog::msgLvlCritical,_("Error creating listening socket.\n"));
		return false;
	};
	m_listeningSocketSet->addSocketToSet(m_listeningSocket);
	return true;
}
Example #13
0
int main(int argc, char **argv)
{
    IPaddress ip;   /* Server address */
    memset(&state, 0, sizeof(state_t));
    state.msg_state = MSG_WRITE;

    if (SDLNet_Init() < 0)
    {
        fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
        finish(EXIT_FAILURE);
    }

    /* Resolve the host we are connecting to */
    if (SDLNet_ResolveHost(&ip, "localhost", SOCKK) < 0)
    {
        fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError());
        finish(EXIT_FAILURE);
    }

    /* Open a connection with the IP provided */
    if (!(state.sd = SDLNet_TCP_Open(&ip)))
    {
        fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError());
        finish(EXIT_FAILURE);
    }

    /* Send messages */
#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(main_loop, 60, 0);
#else
    while (1) main_loop();
#endif

    return EXIT_SUCCESS;
}
Example #14
0
void
ServerConnection::connect(const char* hostname, Uint16 port)
{
    IPaddress ip;

    if(SDLNet_ResolveHost(&ip, hostname, port) == -1)
    {
        printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError());
        exit(1);
    }

    tcpsock = SDLNet_TCP_Open(&ip);
    if(!tcpsock)
    {
        printf("SDLNet_TCP_Open: %s %s:%d\n", SDLNet_GetError(), hostname, port);
        exit(2);
    }
    else
    {
        std::string line = "client_version 1\n";
        SDLNet_TCP_Send(tcpsock, const_cast<char*>(line.c_str()), line.length());

        socketset = SDLNet_AllocSocketSet(1);
        SDLNet_TCP_AddSocket(socketset, tcpsock);
    }
}
Example #15
0
    Client::Client(const char *host, Uint16 port) :
        listener_thread(0),
        mutex(0),
        dx(0),
        dy(0),
        t(0)
    {
        for (int i = 0; i < 32*32; ++i)
            m_grass[i] = 0;

        // connect to localhost at port 9999 using TCP (client)
        IPaddress ip;
        if (SDLNet_ResolveHost(&ip, host, port) < 0)
        {
            printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError());
            throw("Failed to resolve host");
        }

        sock = SDLNet_TCP_Open(&ip);
        if (!sock)
        {
            printf("SDLNet_TCP_Open: %s\n", SDLNet_GetError());
            throw("Failed to open socket");
        }

        mutex = SDL_CreateMutex();
        listener_thread = SDL_CreateThread(listen, this);
    }
Example #16
0
	  int TCP_RECEIVEOBJ::connect()
	  {
	 	sock=0;
		if(SDLNet_ResolveHost(&ip, host, PORT) == -1)
		{
			strcpy(szdata, "SDLNet_ResolveHost: "); strcat(szdata, SDLNet_GetError());
			report_error(szdata); return(FALSE);
		}
		
		sock = SDLNet_TCP_Open(&ip);
		if(!sock)
		{
			strcpy(szdata, "SDLNet_TCP_Open: "); strcat(szdata, SDLNet_GetError());
			report_error(szdata);return(FALSE);
		}
		
		set = SDLNet_AllocSocketSet(1);
		if(!set)
		{
			strcpy(szdata,"SDLNet_AllocSocketSet: "); strcat(szdata, SDLNet_GetError());
			report_error(szdata);return(FALSE);
		}
		
		if (SDLNet_TCP_AddSocket(set, sock) == -1)
		{
			strcpy(szdata,"SDLNet_TCP_AddSocket: ");strcat(szdata, SDLNet_GetError());
			report_error(szdata);return(FALSE);
		}
		if (!sock) return(FALSE);
		cout<<"connected.";
		return(TRUE);
	  }
Example #17
0
ret_code_t network_open_data_connection(context_t * context)
{
	IPaddress ip;
	TCPsocket socket;

	if (SDLNet_ResolveHost(&ip, context->hostname, PORT) < 0)
	{
		werr(LOGUSER, "Can't resolve %s:%d : %s\n", context->hostname, PORT,
				SDLNet_GetError());
		return RET_NOK;
	}

	if (!(socket = SDLNet_TCP_Open(&ip)))
	{
		werr(LOGUSER, "Can't open data connection to %s:%d : %s\n",
				context->hostname, PORT, SDLNet_GetError());
		return RET_NOK;
	}

	context_set_socket_data(context, socket);

	SDL_CreateThread(async_data_recv, "async_data_recv", (void*) context);

	return RET_OK;
}
 int Connection::connect(const std::string &host, int port){
     if( (port == 0) || isSpace(host) ){
         std::cerr << __FILE__ << " " << __LINE__ << ": " << "Connection::connect(string, int): Port can't be 0. Host can't be whitespace." << std::endl;
         return -1;
     }
     IPaddress ip;
     if( SDLNet_ResolveHost(&ip, host.c_str(), port) == -1 ){
         std::cerr << __FILE__ << " " << __LINE__ << ": " << "SDLNet_ResolveHost: " << SDLNet_GetError() << std::endl;
         return -1;
     }
     ScopedMutexLock(pimpl_->dataAccess);
     //make sure is dissconected
     if( pimpl_->userSocket != NULL ){
         SDLNet_TCP_Close( pimpl_->userSocket );
         pimpl_->userSocket = NULL;
     }
     pimpl_->userSocket = SDLNet_TCP_Open(&ip);
     if( pimpl_->userSocket == NULL ){
         std::cerr << __FILE__ << " " << __LINE__ << ": " << "SDLNet_TCP_Open: " << SDLNet_GetError() << std::endl;
         pimpl_->active = false;
         pimpl_->connectTime = 0;
         return -1;
     }
     pimpl_->peer = SDLNet_TCP_GetPeerAddress(pimpl_->userSocket);
     pimpl_->active = true;
     pimpl_->connectTime = SDL_GetTicks();
     return 1;
 }
Example #19
0
int connectionThreadFunc(void *args)
{
	if( !args )
		return 0;
	connectionThreadData* threadData = (connectionThreadData*)args;
	IPaddress addr;
	SDLNet_ResolveHost(&addr, threadData->remoteHost, threadData->remotePort);
	if( addr.host == INADDR_NONE )
	{
		CLog::instance()->log(CLog::msgFlagNetwork, CLog::msgLvlError, _("Can't resolve host '%s'.\n"), threadData->remoteHost);
		return 0;
	};
	threadData->dataSockPtr->m_socket = SDLNet_TCP_Open(&addr);
	if( threadData->dataSockPtr->m_socket == NULL )
	{
		threadData->dataSockPtr->m_sockErrorOccured = true;
		CLog::instance()->log(CLog::msgFlagNetwork, CLog::msgLvlError, _("Error opening socket -- connection to %s failed.\n"), threadData->remoteHost);
		return 0;
	};
	threadData->dataSockPtr->m_remoteHost = threadData->remoteHost;
//	threadData->dataSockPtr->m_remotePort = threadData->remotePort;
	threadData->dataSockPtr->m_lastPing = time(NULL);
	threadData->dataSockPtr->m_lastPong = time(NULL);
	threadData->sockSet->addSocketToSet(threadData->dataSockPtr->m_socket);
	threadData->dataSockPtr->recalculateRemoteHost();
	CLog::instance()->log(CLog::msgFlagNetwork, CLog::msgLvlError, _("Connection to %s established.\n"), threadData->remoteHost);
    return 0;
};
Example #20
0
bool IRC::connect(const std::string &serverName, int serverPort, const std::string &nick)
{
	disconnect();
	
	IPaddress ip;
	socketSet = SDLNet_AllocSocketSet(1);
	if (SDLNet_ResolveHost(&ip, (char *)serverName.c_str(), serverPort)==-1)
	{
		fprintf(stderr, "YOG : ResolveHost: %s\n", SDLNet_GetError());
		return false;
	}

	socket = SDLNet_TCP_Open(&ip);
	if (!socket)
	{
		fprintf(stderr, "YOG : TCP_Open: %s\n", SDLNet_GetError());
		return false;
	}

	SDLNet_TCP_AddSocket(socketSet, socket);
	
	// Here we change the nick on yog for the IRC
	// changing from nick = "nick" to YOGnick = "YOGnick"
	this->nick = "[YOG]" + nick;

	sendString("USER " + this->nick + " undef undef " + PACKAGE_TARNAME + "-" + PACKAGE_VERSION);
	sendString("NICK " + this->nick);

	return true;
}
Example #21
0
bool NetClient::connecttoserver()
{
	//if(SDLNet_ResolveHost(&ip, game_values.hostaddress, 12521) == -1) 
	//if(SDLNet_ResolveHost(&ip, "10.115.8.222", 12521) == -1) 
	//if(SDLNet_ResolveHost(&ip, "10.115.5.65", 12521) == -1) 
	if(SDLNet_ResolveHost(&ip, "192.168.0.2", 12521) == -1) 
	//if(SDLNet_ResolveHost(&ip, "127.0.0.1", 12521) == -1) 
	{
		printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError());
		return false;
	}

	tcpsock = SDLNet_TCP_Open(&ip);
	
    if(!tcpsock) {
		printf("SDLNet_TCP_Open: %s\n", SDLNet_GetError());
		return false;
	}

	/* Allocate the socket set for polling the network */
	socketset = SDLNet_AllocSocketSet(1);
    if (socketset == NULL) {
		printf("Couldn't create socket set: %s\n", SDLNet_GetError());
		return false;
	}

	SDLNet_TCP_AddSocket(socketset, tcpsock);
	
	return true;
}
Example #22
0
bool NetServer::startserver()
{
	socketset = SDLNet_AllocSocketSet(MAXCLIENTS + 1);

    if (socketset == NULL) {
		printf("Couldn't create socket set: %s\n", SDLNet_GetError());
		return false;
	}

	SDLNet_ResolveHost(&ip, NULL, 12521);

	printf("Server IP: %x:%d\n", ip.host, ip.port);

	tcpsock = SDLNet_TCP_Open(&ip);
	
    if (tcpsock == NULL) {
		cleanup();
		printf("Couldn't create server socket: %s\n", SDLNet_GetError());
		return false;
	}

	SDLNet_TCP_AddSocket(socketset, tcpsock);

	return true;
}
Example #23
0
int main(int argc, char **argv)
{
    IPaddress ip;		/* Server address */
    TCPsocket sd;		/* Socket descriptor */
    int quit, len;
    char buffer[512];

    /* Simple parameter checking */
    if (argc < 3)
    {
        fprintf(stderr, "Usage: %s host port\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if (SDLNet_Init() < 0)
    {
        fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
        exit(EXIT_FAILURE);
    }

    /* Resolve the host we are connecting to */
    if (SDLNet_ResolveHost(&ip, argv[1], atoi(argv[2])) < 0)
    {
        fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError());
        exit(EXIT_FAILURE);
    }

    /* Open a connection with the IP provided (listen on the host's port) */
    if (!(sd = SDLNet_TCP_Open(&ip)))
    {
        fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError());
        exit(EXIT_FAILURE);
    }

    /* Send messages */
    quit = 0;
    while (!quit)
    {
        printf("Write something:\n>");
        scanf("%s", buffer);

        len = strlen(buffer) + 1;
        if (SDLNet_TCP_Send(sd, (void *)buffer, len) < len)
        {
            fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError());
            exit(EXIT_FAILURE);
        }

        if(strcmp(buffer, "exit") == 0)
            quit = 1;
        if(strcmp(buffer, "quit") == 0)
            quit = 1;
    }

    SDLNet_TCP_Close(sd);
    SDLNet_Quit();

    return EXIT_SUCCESS;
}
Example #24
0
void Users::connect(Universe *_u){
    u = _u;
    SDLNet_Init();
    SDLNet_ResolveHost(&ip,NULL,port);
    sock = SDLNet_TCP_Open(&ip);
    set = SDLNet_AllocSocketSet(10);
    SDLNet_TCP_AddSocket(set,sock);
}
Example #25
0
Connection* Connection_create(const char* ip, Uint16 port)
{
    Connection* self = (Connection*)calloc(1, sizeof(Connection));
    if(!self)
    {
        return NULL;
    }

    if(SDLNet_ResolveHost(&self->address, ip, port))
    {
        Connection_destroy(&self);
        return NULL;
    }

    if(!(self->socket = SDLNet_TCP_Open(&self->address)))
    {
        Connection_destroy(&self);
        return NULL;
    }

    if(!(self->socket_set = SDLNet_AllocSocketSet(1)))
    {
        Connection_destroy(&self);
        return NULL;
    }

    if(SDLNet_TCP_AddSocket(self->socket_set, self->socket) == -1)
    {
        Connection_destroy(&self);
        return NULL;
    }

    if(SDLNet_CheckSockets(self->socket_set, 5000) == 1)
    {
        Uint8 message = Connection_recv_flag(self);
        if(message == CONNECTED)
        {
            Uint8 buffer[6] = {0};
            Connection_recv_data(self, buffer, 6);

            self->local_address.host = SDLNet_Read32(buffer);
            self->local_address.port = SDLNet_Read16(buffer + 4);
            printf("Successfully connected to server\n");
            return self;
        }
        else if(message == FULL)
        {
            printf("Server is full\n");
        }
    }
    else
    {
        printf("Server is not responding\n");
    }

    Connection_destroy(&self);
    return NULL;
}
CHostSocket::CHostSocket(CIPAddress& sdlIpAddress ) 
	: log("TcpSocketHost", CXmlSettings::Inst()->GetLoggerSettings()->logLevel)
{
	IPaddress hostIp = sdlIpAddress.GetIPAddress();
	if(!(_socket = SDLNet_TCP_Open(&hostIp)))
	{
		SDLNet_FreeSocketSet(_socketSet);
	}
}
Example #27
0
TCPsocket Client::Server_TCP_Connect ()
{
    TCPsocket socket = SDLNet_TCP_Open (&serverAddress);
    if (!socket)
    {
        fprintf (stderr, "error tcp connecting to the server: %s\n", SDLNet_GetError());
    }
    return socket;
}
Example #28
0
/**
 * @brief Constructor principal
 *
 * @param the_ip_address Dirección ip para abrir el socket.
 *
 * Se encarga de iniciar el objeto del socket a partir de una estructura de datos CIpAddress. En caso de no poder
 * crear el socket, SDL_net generará un error.
 */
CHostSocket::CHostSocket(CIpAddress& the_ip_address)
{
  CTcpSocket();
  IPaddress iph = the_ip_address.GetIpAddress();
  if(!(m_Socket = SDLNet_TCP_Open(&iph)))
  {
    SDLNet_FreeSocketSet(set);
    std::cerr << "SDLNet_TCP_Open: " << SDLNet_GetError() << std::endl;
  }
}
Example #29
0
static __inline__ TCPsocket snTCPOpen(IPaddress *ip)
{
  TCPsocket socket = NULL ;

  lockSDLNet();
  socket = SDLNet_TCP_Open(ip);
  unlockSDLNet();

  return socket;
}
Example #30
0
void TCOD_noteye_init() {

  if(scr) return;
  
  if(tnoteye.port == 0) tnoteye.port = 6678;
  if(tnoteye.quality == 0) tnoteye.quality = 256;
  if(tnoteye.minTicks == 0) tnoteye.minTicks = 50;
  if(tnoteye.name == NULL) tnoteye.name = "libtcod";
  if(tnoteye.maxClients <= 0) tnoteye.maxClients = 1;
  if(tnoteye.maxClients > MAXCLIENT) tnoteye.maxClients = MAXCLIENT;
  
  objs.push_back(NULL);
  objs.push_back(&gfx);  
  exsurface=SDL_CreateRGBSurface(SDL_SWSURFACE,16,16,32,0,0,0,0);

  img = new Image(8*32, 16*8);
  img->title = TCOD_ctx.font_file;
  registerObject(img);

  fontcount = TCOD_ctx.fontNbCharHoriz * TCOD_ctx.fontNbCharVertic;
  ourfont = new int[fontcount];

  for(int ch=0; ch<fontcount; ch++) {
    int ascii= TCOD_ctx.ascii_to_tcod[ch];
    
    int ti = 
      addTile(img, 
        (ascii%TCOD_ctx.fontNbCharHoriz)*TCOD_ctx.font_width, 
        (ascii/TCOD_ctx.fontNbCharHoriz)*TCOD_ctx.font_height, 
        TCOD_ctx.font_width, TCOD_ctx.font_height, 0);

    (byId<TileImage> (ti, LS_image))->chid = ch;

    ourfont[ch] = ti;
    }

  scr = new Screen;
  registerObject(scr);
  
  IPaddress ip;
  noteye_initnet();
  
  if(SDLNet_ResolveHost(&ip, NULL, tnoteye.port) != 0) {
    printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError());
    exit(1);
    }

  TCPsocket skt = SDLNet_TCP_Open(&ip);
  if(!skt) {
    printf("SDLNet_TCP_Open: %s\n", SDLNet_GetError());
    exit(1);
    }
  
  server = new TCPServer(skt);
  }