Example #1
0
static void handle_newgame(int sock, const char* args) {
    int res = sscanf(args, "%d %d %d %d", &_board_height, &_board_width, &my_ID, &thekey);
    if (res != 4) {
        printf("CLIENT LIBRARY INTERNAL ERROR: "
                "Incorrect arguments on NEWGAME.\n");
    }
    state = STATE_INTERNAL;
    alarm(1);
    clientInit(_board_height, _board_width, my_ID);
    alarm(0);
    client_printf(sock, "READY %d\r\n", thekey);
}
Example #2
0
static void handle_newgame(int sock, const char* args) {
    int res = sscanf(args, "%d %d %d %d %d", &player_count, &board_size, &starting_health, &my_ID, &thekey);

    if (res != 5) {
        printf("CLIENT LIBRARY INTERNAL ERROR: "
                "Incorrect arguments on NEWGAME.\n");
    }
    state = STATE_INTERNAL;
    alarm(1);
    clientInit(player_count, board_size, starting_health, my_ID);
    alarm(0);
    client_printf(sock, "READY %d\r\n", thekey);
}
int main(int argc, char const *argv[])
{
    if (argc != 3) {
        fprintf(stderr, "usage: %s <server address> <port>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    if (!isValidArguments(argc, argv)) {
        fprintf(stderr, "Invalid Arguments\n");
        exit(EXIT_FAILURE);
    }
    init();
    int port;
    sscanf(argv[2], "%d", &port);
    int sockfd = clientInit(argv[1], port);
    printf("\n\nNetwork Programming Homework 1\n\nConnected to %s:%s\n", argv[1], argv[2]);
    TCPClient(sockfd, argv[1]);
    closeClient(sockfd);
    return 0;
}
Example #4
0
void Base3DView::initializeGL()
{
#ifdef WIN32   
    if(gExtensionInit()) qDebug()<<"GL Extensions checked.";
#endif
	qglClearColor(m_backgroundColor.dark());

    glEnable(GL_DEPTH_TEST);
	glEnable(GL_COLOR_MATERIAL);
	glEnable(GL_TEXTURE_2D);
	glShadeModel(GL_SMOOTH);
	glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
	glHint( GL_POLYGON_SMOOTH_HINT, GL_NICEST );
    // glEnable(GL_MULTISAMPLE);
	glDepthFunc(GL_LEQUAL);
	getDrawer()->initializeProfile();
	m_hud->reset();
	
	clientInit();
}
Example #5
0
int 
main(int argc, char **argv)
{
  Client c;

  initGlobals(argc, argv);

  if (clientInit(&c) < 0) {
    fprintf(stderr, "ERROR: clientInit failed\n");
    return -1;
  }    

  // ok startup our connection to the server
  if (startConnection(&c, globals.host, globals.port, update_event_handler)<0) {
    fprintf(stderr, "ERROR: startConnection failed\n");
    return -1;
  }

  shell(&c);

  return 0;
}
Example #6
0
// Main program entry point
int main(int argc, char **argv) {
    for (int i = 0; i < (1 + MAX_PLAYERS); i++)
        threadsFree[i] = -1;

    setProgName(argv[0]);
    debugDisable();
    infoPrint("Server Gruppe 01");
    userInit();

    // Create PID lock file or exit if it already exists
    debugPrint("Making sure we're running only once...");
    if (singleton(LOCKFILE) != 0)
        return 1;

    // Socket structure that could be modified by the command line arguments
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    server.sin_port = htons(PORT); // Use the default port defined in "common"!

    // Prepare parsing the command line options using getopt()
    debugPrint("Parsing command line options...");
    const char* short_options = "hvp:";
    struct option long_options[] = {
        { "help", no_argument, 0, 'h' },
        { "verbose", no_argument, 0, 'v' },
        { "port", required_argument, 0, 'p' },
        { NULL, 0, NULL, 0 }
    };

    // Actual getopt() loop
    int option_index = 0;
    int loop = 1;
    while (loop != 0) {
        int c = getopt_long(argc, argv, short_options, long_options, &option_index);
        switch (c) {
            // Show help text when using -h
            case 'h':
                show_help();
                exit(1);
                break;

            // Enable verbose (debug) output
            case 'v':
                debugEnable();
                break;

            // Set port to listen on
            case 'p':
                if(optarg) {
                    if (isOnlyDigits(optarg)) {
                        server.sin_port = htons(atoi(optarg));
                    } else {
                        errorPrint("Port has to be a decimal number!");
                        exit(1);
                    }
                }
                break;

            // Unknown option, show error & help message
            default:
            case '?':
                errorPrint("Option not implemented yet -- %s (%c)", argv[optind-1], c);
                show_help();
                exit(1);
                break;

            // All options have been parsed
            case -1:
                loop = 0;
                break;
        }
    }

    infoPrint("Serverport: %i", ntohs(server.sin_port));

    // Create the pipes that will be used to communicate with the loader
    debugPrint("Creating Pipes...");
    if (!createPipes())
        return 1;

    // Actually fork and run the loader as child process
    debugPrint("Forking to run loader...");
    if (!forkLoader())
        return 1;

    debugPrint("Starting Threads...");

    // Start the score agent thread
    if (pthread_create(&threads[0], NULL, scoreThread, NULL) != 0) {
        threadsFree[0] = -2;
        errnoPrint("pthread_create");
        return 1;
    }

    clientInit();

    // Create the listening socket
    debugPrint("Creating socket...");
    int listen_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (listen_socket == -1) {
        errnoPrint("socket");
        return 1;
    }

    // Enable address reusing, so we don't get bind errors
    int on = 1;
    setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    // Register our Interrupt Signal handler
    signal(SIGINT, intHandler);

    // Store the listening socket in our user database
    userSetMainSocket(listen_socket);

    // Actually bind the listening socket
    if (bind(listen_socket, (struct sockaddr*) &server, sizeof(struct sockaddr_in)) == -1) {
        errnoPrint("bind");
        close(listen_socket);
        closePipes();
        loaderCloseSharedMemory();
        return 1;
    }

    // Prepare the pselect() timeout data structure
    fd_set fds;
    struct timespec ts;
    ts.tv_sec = 0;
    ts.tv_nsec = SOCKET_TIMEOUT * 1000000;
    sigset_t blockset;
    sigfillset(&blockset);
    sigdelset(&blockset, SIGINT);

    // Main thread main loop, waiting for new connections
    debugPrint("Waiting for connections...");
    while (getRunning()) {
        // Listen to the listening socket
        if (listen(listen_socket, MAX_QUERYS) == -1) {
            errnoPrint("listen");
            close(listen_socket);
            closePipes();
            loaderCloseSharedMemory();
            cleanCategories();
            return 1;
        }

        // Wait for activity on the listening socket
        FD_ZERO(&fds);
        FD_SET(listen_socket, &fds);
        int retval = pselect(listen_socket + 1, &fds, NULL, NULL, &ts, &blockset);
        if (retval == -1) {
            if (errno == EINTR) {
                // We should exit because the user pressed Ctrl + C
                close(listen_socket);
                closePipes();
                loaderCloseSharedMemory();
                cleanCategories();
                return 0;
            } else {
                // pselect encountered an error!
                errnoPrint("select");
                close(listen_socket);
                closePipes();
                loaderCloseSharedMemory();
                cleanCategories();
                return 1;
            }
        } else if (retval == 0) {
            // Nothing happened and pselect timed out
            continue;
        } else {
            // We have a new connection, accept it
            struct sockaddr_in remote_host;
            socklen_t sin_size = sizeof(struct sockaddr_in);
            int client_socket = accept(listen_socket, (struct sockaddr *) &remote_host, &sin_size);
            if (client_socket == -1) {
                errnoPrint("accept");
                close(listen_socket);
                closePipes();
                loaderCloseSharedMemory();
                cleanCategories();
                return 1;
            }

            debugPrint("Got a new connection! Performing Login...");
            loginHandleSocket(client_socket);
        }
    }

    // Clean up behind ourselves
    close(listen_socket);
    closePipes();
    loaderCloseSharedMemory();
    cleanCategories();

    pthread_exit(NULL);
    return 0;
}
Example #7
0
File: main.cpp Project: HrochL/CWSL
///////////////////////////////////////////////////////////////////////////////
// Main function
int main(int argc, char **argv)
{WSADATA wsd;
 SOCKET sClient;
 struct sockaddr_in local, client;
 int iAddrSize;
 char fileName[_MAX_PATH + 1];
 char *pFN, *pc;

 // create the prefix and suffix for the shared memories names
 strcpy(gPreSM, "CWSL");
 strcpy(gPostSM, "Band");
 ::GetModuleFileName(NULL, fileName, _MAX_PATH);
 #define BASE_FNAME "CWSL_Net"
 pFN = strstr(fileName, BASE_FNAME);
 if (pFN != NULL)
 {
  pFN += strlen(BASE_FNAME);
  for (pc = pFN; (*pc != '\0') && (*pc != '.'); pc++);
  *pc = '\0';
  strcat(gPostSM, pFN);
 }

 // print info
 printf("Starting (%s#%s) ...\n", gPreSM, gPostSM);

 // initialize slots
 clientInit();

 // initialize sockets
 if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
 {printf("Failed to load Winsock!\n");
  return 1;
 }

 // create our listening socket
 sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
 if (sListen == SOCKET_ERROR)
 {printf("socket() failed: %d\n", WSAGetLastError()); return 1;}

 // bind it to our well-known port
 local.sin_addr.s_addr = htonl(INADDR_ANY);
 local.sin_family = AF_INET;
 local.sin_port = htons(LISTEN_PORT);
 if (bind(sListen, (struct sockaddr *)&local, sizeof(local)) == SOCKET_ERROR)
 {printf("bind() failed: %d\n", WSAGetLastError()); return 1;}
    
 // set socket into listen mode
 listen(sListen, 8);
 
 // register console control handler
 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)ControlHandler, TRUE))
  printf("Can't register console control handler!\n");
    
 // print info
 printf("Started\n");

 // main loop
 while (1)
 {// perform a blocking accept() call
  iAddrSize = sizeof(client);
  sClient = accept(sListen, (struct sockaddr *)&client, &iAddrSize);
  if (sClient == INVALID_SOCKET)
  {printf("accept() failed: %d\n", WSAGetLastError()); break;}
    
  // create new client thread
  if (!clientNew(&client, sClient)) printf("clientNew() failed: %d\n", GetLastError());
 }
 
 // print info
 printf("Stopping ...\n");

 // close listen socket
 closesocket(sListen);

 // free all clients
 clientFree();
 
 // cleanup sockets
 WSACleanup();
 
 // print info
 printf("Stopped\n");

 // that't all
 return 0;
}
Example #8
0
bool GameLabyrinth::init(Config& _conf, Input& _input)
{
	if (!GameFreeScene::init(_conf, _input))
	{
		return false;
	}
// resources
    character_model = loadGraphObject(_conf, "character.model");

    if (conf->getb("labyrinth.randomize", false))
    {
        srand((unsigned int)(globalTimer.timestamp()*1000));
    }
    else
    {
        srand((unsigned int)(conf->geti("labyrinth.rand_seed", 0)));
    }

    if (conf->gets("camera.mode", "fixed") == "fixed")
    {
	    cameraMode = C_FIXED;
        spectator.camera.setDirection(v3(1, 1, -0.3f));
    }
    else
    {
	    cameraMode = C_FREE;
    }

	if (!initAgeia())
	{
		abort_init("PhysX", "Cannot init PhysX");
		return false;
	}
	
// network
    std::string net_role_str = conf->gets("net.role", "server");

    if (!loadScene(conf->find("scene")))
	{
		return false;
	}

	if (net_role_str == "server")
    {
        if (!serverInit())
        {
            return false;
        }
        game_state = GAME_PLAYING;
    }
    else if (net_role_str == "client")
    {
        if (!clientInit())
        {
            return false;
        }
    }
    else
    {
		abort_init("net", "Unknown net role '" + net_role_str + "'");
    }

    createPhysicWorld();

    netTimerSend.start();
    netTimerReceive.start();
    netTimerReconnect.start();
    refresh_needed = true;
    cell_visibility_set.clear();
    injected_objects.clear();

    return true;
}
Example #9
0
int 
main(int argc, char **argv)
{
  Client c;  
  
  if (!FASTINPUTMODE)
      fprintf(stderr, "Type 'connect <host:port>' to connect to a game.\n");

  if (clientInit(&c) < 0) {
    fprintf(stderr, "ERROR: clientInit failed\n");
    return -1;
  }    

  initGlobals(argc, argv);

  if (FASTINPUTMODE) {
    startConnection(&c, globals.host, globals.port, update_event_handler);
    doRPCCmd(&c, 'q'); //query for the map
    if (STRESS_TEST==1)
      proto_client_hello(c.ph);
  }    

  shell(&c);
  // Cannot put shell on a separate thread because fget() function doesn't work for some reason
  // pthread_t tid;
  // pthread_create(&tid, NULL, shell, &c);
  Proto_Client *proto_client = c.ph;
  Player *me = getPlayer(&proto_client->game, proto_client->playerID);

  if (DISPLAYUI==1) {

    // If I am not the host and we are stress testing, I should be wandering
    if (me->isHost==0 && STRESS_TEST==1) {
         // Wander(&c, 0);
        docmd(&c, "test\n");

    }
    // The host will be the only ones that has UI showing, other players just wonder
    else 
    {
      //window will be consistently 20x20
      // pthread_t tid;
      // pthread_create(&tid, NULL, shell, NULL);

      // Init for UI stuff
      tty_init(STDIN_FILENO);

      ui_init(&(ui));

      // WITH OSX ITS IS EASIEST TO KEEP UI ON MAIN THREAD
      // SO JUMP THROW HOOPS :-(
      Proto_Client *client = (Proto_Client *) c.ph;
      Player *me = getPlayer(&client->game, client->playerID);

      doRPCCmd(&c, 'q'); //query for the map
      ui_main_loop(ui, (32 * WINDOW_SIZE), (32 * WINDOW_SIZE), &client->game, me, &c);
    }

  }


  // launchUI(&c);
    
  return 0;
}