int main(int argc, char **argv){
	// port number that listens for client connections
	int port; 
	// check for server user input errors 
	// server expects two command-line arguments, "ftserver" and the desired port number
	if (argc != 2) {
		fprintf(stderr, "Error: Use ftserver <server-port>\n");
		exit(1);
	}
	// port number must be a number
	if (!isNumber(argv[1], &port)) {
		fprintf(stderr, "ftserver: Server port must be a number!\n");
		exit(1);
	}
	// start the server until an interrupt signal is received
	startServer(port);

	exit(0);
}
Пример #2
0
int main() {

    // Create the mouse device
    int fd = createDevice();
    if (fd < 0) {
        return EXIT_FAILURE;
    }

    // Start the server. The received data will be sent to the mouseHandler()
    // callback function
    if (0 != startServer(mouseHandler, (void *) &fd)) {
        return EXIT_FAILURE;
    }

    // Destroy the mouse device
    destroyDevice(fd);

    return EXIT_SUCCESS;
}
Пример #3
0
int main()
{
    //初始化日志系统
    initLogger();

    //加载配置
    CServer::getInstance()->getConf()->loadConf();

    //启动topo管理模块
    if (!CServer::getInstance()->getTopoMgr()->init())
    {
        LOG_ERROR("topo module init failure");
        return 0;
    }

    //启动服务
    startServer();
    return 0;
}
Пример #4
0
void procMenu()
{
    switch(ch)
    {
    case 's':
    case 'S':
    case '1':
        startServer();
        break;

    case 'e':
    case 'E':
    case '2':
        exitProc();
        break;

    default:
        defProc();
    }
}
Пример #5
0
void foo_server(int &a)
{
    struct sockaddr_in clientaddr;
    socklen_t addrlen;
    char c;    

    //Default Values PATH = ~/ and PORT=10000
    char PORT[6];
    ROOT = getenv("PWD");
    strcpy(PORT,"55572");
    strcpy(ROOT,"/home/");
    int slot=0;
    
    printf("Server started at port no. %s%s%s with root directory as %s%s%s\n","\033[92m",PORT,"\033[0m","\033[92m",ROOT,"\033[0m");
    // Setting all elements to -1: signifies there is no client connected
    int i;
    for (i=0; i<CONNMAX; i++)
        clients[i]=-1;
    startServer(PORT);

    // ACCEPT connections
    while (1)
    {
        addrlen = sizeof(clientaddr);
        clients[slot] = accept (listenfd, (struct sockaddr *) &clientaddr, &addrlen);

        if (clients[slot]<0)
            perror ("accept() error");
        else
        {
            if ( fork()==0 )
            {
                respond(slot);
                exit(0);
            }
        }

        while (clients[slot]!=-1) slot = (slot+1)%CONNMAX;
    }

}
Пример #6
0
int main( int argc, char* argv[]) {
	int c;
	
	initialization();

	while((c = getopt(argc, argv, "dhc:i:l:p:")) != -1) {
		switch(c) {
			case 'd':
				dFlag = 1;
				lFlag = 0;
				break;
			case 'h':
				hFlag = 1;
				usage();
				break;
			case 'c':
				cFlag = 1;
				// to do
				break;
			case 'i':
				iFlag = 1;
				server_addr = optarg;
				break;
			case 'l':
				lFlag = 1;
				dFlag = 0;
				// to do
				break;
			case 'p':
				pFlag = 1;
				server_port = optarg;
		}
	}
	
	argc -= optind;
	argv += optind;
	
	startServer();
	exit(0);

}
void ServerManager::serverFinish(int exitCode, QProcess::ExitStatus exitStatus)
{
    QProcess *server = qobject_cast<QProcess *>(sender());
    if (server) {
        //server->close();  // long blocking..
        server->deleteLater();
        int id = serversStatus.take(server);

        if (isRunning()) {
            if (exitCode != 127) {  // 127 : for auto reloading
                tSystemError("Detected a server crashed. exitCode:%d  exitStatus:%d", exitCode, (int)exitStatus);
            }
            startServer(id);
        } else {
            tSystemDebug("Detected normal exit of server. exitCode:%d", exitCode);
            if (serversStatus.count() == 0) {
                Tf::app()->exit(-1);
            }
        }
    }
}
Пример #8
0
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: main
--
-- DATE: March 10, 2014
--
-- REVISIONS:
--
-- DESIGNER: Robin Hsieh
--
-- PROGRAMMER: Robin Hsieh
--
-- INTERFACE: int main (int argc , char *argv[])
--              int argc:       The number of the arguments put in from the command line.
--              char *argv[]:   The array of char* of the arguments
--
-- RETURNS: int
--              Returns an int when program terminates.
--
-- NOTES:
-- This function is to start the server program to be able to allow clients to connect, and act as a echo server
-- that will send message from 1 client, to the rest of other clients connected. This program can also star the
-- client program that will be able to connect to a server, and send messages to that server.
--
------------------------------------------------------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
    char username[128];
    char ip[128];
    int port;

    if(argc == 3)
    {
        if(strcmp(argv[1], "server") == 0)
        {
            port = atoi(argv[2]);
            startServer(port);
        }
        else
        {
            exit_message();
        }
    }
    else if(argc == 5)
    {
        if(strcmp(argv[1], "client") == 0)
        {
            strcpy(username, argv[2]);
            strcpy(ip, argv[3]);
            port = atoi(argv[4]);

            startClient(username, ip, port);
        }
        else
        {
            exit_message();
        }
    }
    else
    {
        exit_message();
    }

    return 0;
}
void FakeAdapter::start()
{
	USES_CONVERSION;
	HRESULT hr;
	// NOTE start should return in atimely fashion

	//hResult = CoCreateInstance(	clsid,
	//		NULL,
	//		CLSCTX_SERVER,
	//		IID_IOPCServer,
	//		(void**)&_pIOPCServer 
	//		);
	// Only works for local thread ...
	_appdispatch.CoCreateInstance(L"PCDLRN.Application");
	//pSinkObj->DispEventAdvise(_appdispatch);
	// look at http://369o.com/data/books/atl/0321159624/ch03lev1sec4.html for name invoking with parameter


	// I'm going to need an override enter and exit thread loop for ComInitialize - thread issue
	startServer();

}
Пример #10
0
int main(int argc,char *argv[]){

	if(argc != 2){
		fprintf(stderr, "USAGE : %s portnumber\n",argv[0]);
		return 1;
	}

	signal(SIGINT,sighandler);
	signal(SIGCHLD,sigChldHandler);

	gPid_server = getpid();
	gI_serverPortNum = atoi(argv[1]);
	gettimeofday(&startTime,NULL);

	startServer(gI_serverPortNum);

	gettimeofday(&endTime,NULL);
	diffTime=getTimeDif(startTime,endTime);
	printf("[%ld] server closed in %ld ms\n",(long)gPid_server,diffTime);

	return 0;
}
Пример #11
0
//--------Mainline--------//
int main (int argc, char *argv[]) {
    int numberServedCounter;
    int serverSocket;

    //check that these store 1, 2 & 4 bytes as required
    assert (sizeof(bits8) == 1);
    assert (sizeof(bits16) == 2);
    assert (sizeof(bits32) == 4);

    serverSocket = startServer();

    numberServedCounter = 0;

    while (numberServedCounter < NUMBER_OF_PAGES_TO_SERVE){
        servePage(numberServedCounter, serverSocket);
        numberServedCounter++;
    }

    // close the server connection after we are done
    close (serverSocket);

    return EXIT_SUCCESS; 
}
Пример #12
0
/*  PURPOSE:  To secure port 'PORT_NUMBER' to listen to clients, to make
 *      'NUM_CLIENTS' POSIX threads to handle that number of clients, to
 *      display the number of chars processed by either thread as they are
 *      processed, and to close windowing, mutex locking and the socket when
 *      finished.  Returns EXIT_SUCCESS on succes or EXIT_FAILURE otherwise.
 */
int main ()
{
  int       socketDs;
  int       clientIn;
  int       clientIn1;
  pthread_t clientThread[NUM_CLIENTS];

  if  ( (socketDs = startServer()) == -1 )
  {
    fprintf(stderr,"Error connecting to socket.\n");
    return(EXIT_FAILURE);
  }

  startWindow();

    int connectDs = accept(socketDs,NULL,NULL);
    doServer(connectDs);


  stopWindow();
  stopServer(socketDs);
  return(EXIT_SUCCESS);
}
Пример #13
0
void *runMasterSlave(char* myAddress){
//Hier gaan we een rij van laadpalen bijhouden en tegelijk een server runnen waarop nieuwe laadpalen zich kunnen "aanmelden".
//Verder moeten de clients zich met deze server connecteren waarna de maser de clients verbindt met de auto.
	char* tekst=malloc(tekstlengte*sizeof(char*));
	char* buffer=malloc(bufferlengte*sizeof(char*));
	struct sockaddr_storage client_addr;
	socklen_t clilen;
	int socket2, error;
	struct arg input=startServer(poort-2,myAddress);
	IPAdressen=malloc(max_laadpalen*sizeof(char*));
	aantal=1;
	IPAdressen[0]=malloc(IPLengte);
	sprintf(IPAdressen[0],"%s",myAddress);
	while(1){
		//We nemen aan dat de client/andere laadpaal maar 1 boodschap verzend en ontvangt, zodat we hiervoor geen nieuwe thread gaan aanmaken
		input.hints.ai_flags=AI_PASSIVE;
		memset(&client_addr, 0, sizeof(client_addr));
		clilen=16;
		socket2=accept(input.socket1, (struct sockaddr *)&client_addr, &clilen);
		
		if(socket2<0){
			printf("problemen bij accept, error nummer %i, boodschap: %s\n",socket2, gai_strerror(socket2));
			return NULL;
		}
		printf("de clilen is %i\n",clilen);

		//Hier moeten we het tekstobject omvormen tot een json object en dit json object vervolgens uitlezen en verwerken.
		error=read(socket2,buffer,255);
		tekst=setVariables(buffer);
		error=send(socket2,tekst,strlen(tekst)*sizeof(char),input.hints.ai_flags);
		if(error<0){
			printf("problemen bij verzenden van hetpakket\n");
		}

		close(socket2);
	}
}
Пример #14
0
int main(int argc, char *argv[])
{
	struct hostent *he;
	int i = 0;
	pthread_t exitThread;
	int rc;
	
    //int sockfd;
    /*struct sockaddr_in their_addr; // connector's address information
    
    //int numbytes;
    */
    // status vars
    int startServerStatus;
    int stopServerStatus;
    /*
    // parameters
    unsigned int serverPort;
    unsigned long serverIp;*/

/*
	printf("\n############################\n");
	printf("UDP client for TechGI 4 2014\n");
	printf("############################\n\n");
    
    if (argc != 3) {
        fprintf(stderr,"Required: serverName|serverIp serverPort\n");
        exit(1);
    }
    
    //Resolv hostname to IP Address
    if ((he=gethostbyname(argv[1])) == NULL) {  // get the host info
        herror("gethostbyname");
        exit(1);
    }
    
    // assign parameters
    serverPort = atoi(argv[2]);
	memcpy(&serverIp, he->h_addr_list[0], he->h_length); // assign serverIp
	
	// prepare vars
	buffer = malloc(0);*/
	
	
	/* ******************************************************************
    TEST
    ******************************************************************* */

    
    
    // setup servers
    he = gethostbyname("127.0.0.1");
    
    // server 1
    servers[0].id = 42;
    memcpy(&servers[0].address, he->h_addr_list[0], he->h_length);
    servers[0].port = 20010; 
    
    // server 2
    servers[1].id = 106;
    memcpy(&servers[1].address, he->h_addr_list[0], he->h_length);
    servers[1].port = 20011; 
    
    // server 3
    servers[2].id = 170;
    memcpy(&servers[2].address, he->h_addr_list[0], he->h_length);
    servers[2].port = 20012; 
    
    // server 4
    servers[3].id = 234;
    memcpy(&servers[3].address, he->h_addr_list[0], he->h_length);
    servers[3].port = 20013; 
    
    // start all servers
    
    for(i=0;i<4;i++) {
		startServerStatus = startServer(servers[i], ((i==0)?servers[4]:servers[i-1]), (i==(4-1))?servers[0]:servers[i+1]);
		printf("Start server: %d - %s\n", servers[i].id, (startServerStatus>0)?"success":"fail");
	}
    
    
   /* int startServerStatus = startServer(newOne, prev, next);
    printf("startServerStatus: %d\n", startServerStatus);
    
    int stopServerStatus = stopServer();
    printf("stopServerStatus: %d\n", stopServerStatus);*/
    
    /* ******************************************************************
    TO BE DONE: Create socket
    ******************************************************************* */


    //setup transport address
    /*their_addr.sin_family = AF_INET;     
    their_addr.sin_port = htons(serverPort);
    their_addr.sin_addr = *((struct in_addr *)he->h_addr);
    memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);*/


    /* ******************************************************************
    TO BE DONE:  Binding
    ******************************************************************* */
    
	rc = pthread_create(&exitThread, NULL, &listenInput, NULL );
    if( rc != 0 ) {
        printf("Couldn't create exitThread.\n");
        return EXIT_FAILURE;
    }
    
    pthread_join(exitThread, NULL );
    
    for(i=0;i<4;i++) {
		stopServerStatus = stopServer(servers[i]);
		printf("Stop server: %d - %s\n", servers[i].id, (stopServerStatus>0)?"success":"fail");
	}

    /* ******************************************************************
    TO BE DONE:  Send data
    ******************************************************************* */

    /* ******************************************************************
    TO BE DONE:  Close socket
    ******************************************************************* */

	// free mem
	cleanUp();

    return 0;
}
Пример #15
0
int main(int argc, char *argv[])
{
	enum kCommand command = kReadCommand;
	static struct option longopts[] = {
		{"server", no_argument, NULL, 'S'},
		{"version", no_argument, NULL, 'V'},
		{"help", no_argument, NULL, 'h'},
		{"readonly", no_argument, NULL, kReadCommand},
		{"readwrite", no_argument, NULL, kReadWriteCommand},
		{"savereadwrite", no_argument, NULL, kSaveReadWriteCommand},
		{NULL, 0, NULL, 0}
	};
	
	longopts[3].flag = &command;
	longopts[4].flag = &command;
	longopts[5].flag = &command;
	
	char server_flag = 0;
	
	char ch;
	while ((ch = getopt_long(argc, argv, "Vh", longopts, NULL)) != -1) {
		switch (ch) {
			case 'S':
				server_flag = 1;
				break;
			case 'V':
				printVersion();
				exit(0);
				break;
			case 'h':
				printHelp();
				exit(0);
				break;
			default:
				printUsage();
				exit(0);
				break;
		}
	}
	
	if (server_flag) {
		// try to connect to launchd
		int socket;
		if ((socket = getSocketFromLaunchd()) != -1) {
			atexit(sleepBeforeQuit);
			startServer(socket);
			CFRunLoopRun();
		} else {
			fprintf(stderr, "Could not connect to launchd, exiting.\n");
			exit(-1);
		}
	} else { /* non-server mode */
		if (argc <= optind) {
			fprintf(stderr, "No device given.\n");
			exit(-1);
		}
		char *path = argv[optind];
		switch (command) {
			case kReadCommand:
				readOnlySurfaceScan(path, fileno(stdout));
				break;
			case kSaveReadWriteCommand:
				break;
			case kReadWriteCommand:
				break;
		}
	}
}
void FakeAdapter::start()
{
  startServer();
}
Пример #17
0
Файл: web.c Проект: cocojk/major
int main(int argc, char* argv[])
{
		struct sockaddr_in clientaddr;
		socklen_t addrlen;
		char c;


		//Default Values PATH = ~/ and PORT=10000
		int slot=0;

		//Parsing the command line arguments
		while ((c = getopt (argc, argv, "p:r:")) != -1)
				switch (c)
				{
						case 'r':
								ROOT = malloc(strlen(optarg));
								strcpy(ROOT,optarg);
								break;
						case 'p':
								PORT = malloc(strlen(optarg));
								strcpy(PORT,optarg);
								break;
						case '?':
								fprintf(stderr,"Wrong arguments given!!!\n");
								exit(1);
						default:
								exit(1);
				}

		printf("Server started at port no. %s%s%s with root directory as %s%s%s\n","\033[92m",PORT,"\033[0m","\033[92m",ROOT,"\033[0m");
		// Setting all elements to -1: signifies there is no client connected
		int i;
		for (i=0; i<CONNMAX; i++)
				clients[i]=-1;







		startServer(PORT);


		pid_t pid;

		pid_t chpid;
		int statusch;


				while(1)
				{
		addrlen = sizeof(clientaddr);
		clients[slot] = accept (listenfd, (struct sockaddr *) &clientaddr, &addrlen);
		

		if (clients[slot]<0)
		{
			error ("accept() error");
		
			break;
		}
		else if((pid = fork())<0)
						{

						printf("fork error \n");

		//All further send and recieve operations are DISABLED...
		close(clients[slot]);
		clients[slot]=-1;
		continue;
		}
		else if(pid==0)
		{



	
		 					
		respond(slot); 

									//wait 
			
			}
			else
			{


		//All further send and recieve operations are DISABLED...
		close(clients[slot]);
		clients[slot]=-1;
		continue;
		}

		}
		 
		return 0;


}
Пример #18
0
int
main(int argc, char *argv[])
{
    register char **sptr = server;
    register char **cptr = client;
    register char **ptr;
    int pid;
    int client_given = 0, server_given = 0;
    int client_args_given = 0, server_args_given = 0;
    int start_of_client_args, start_of_server_args;
    struct sigaction sa, si;
#ifdef __APPLE__
#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
    vproc_transaction_t vt;
#endif
#endif

    program = *argv++;
    argc--;
    /*
     * copy the client args.
     */
    if (argc == 0 ||
        (**argv != '/' && **argv != '.')) {
        for (ptr = default_client; *ptr; )
            *cptr++ = *ptr++;
    } else {
        client_given = 1;
    }
    start_of_client_args = (cptr - client);
    while (argc && strcmp(*argv, "--")) {
        client_args_given++;
        *cptr++ = *argv++;
        argc--;
    }
    *cptr = NULL;
    if (argc) {
        argv++;
        argc--;
    }

    /*
     * Copy the server args.
     */
    if (argc == 0 ||
        (**argv != '/' && **argv != '.')) {
        *sptr++ = default_server;
    } else {
        server_given = 1;
        *sptr++ = *argv++;
        argc--;
    }
    if (argc > 0 && (argv[0][0] == ':' && isdigit(argv[0][1])))
        displayNum = *argv;
    else
        displayNum = *sptr++ = default_display;

    start_of_server_args = (sptr - server);
    while (--argc >= 0) {
        server_args_given++;
        *sptr++ = *argv++;
    }
    *sptr = NULL;

    /*
     * if no client arguments given, check for a startup file and copy
     * that into the argument list
     */
    if (!client_given) {
        char *cp;
        Bool required = False;

        xinitrcbuf[0] = '\0';
        if ((cp = getenv("XINITRC")) != NULL) {
            snprintf(xinitrcbuf, sizeof(xinitrcbuf), "%s", cp);
            required = True;
        } else if ((cp = getenv("HOME")) != NULL) {
            snprintf(xinitrcbuf, sizeof(xinitrcbuf),
                     "%s/%s", cp, XINITRC);
        }
        if (xinitrcbuf[0]) {
            if (access(xinitrcbuf, F_OK) == 0) {
                client += start_of_client_args - 1;
                client[0] = xinitrcbuf;
            } else if (required) {
                Error("warning, no client init file \"%s\"", xinitrcbuf);
            }
        }
    }

    /*
     * if no server arguments given, check for a startup file and copy
     * that into the argument list
     */
    if (!server_given) {
        char *cp;
        Bool required = False;

        xserverrcbuf[0] = '\0';
        if ((cp = getenv("XSERVERRC")) != NULL) {
            snprintf(xserverrcbuf, sizeof(xserverrcbuf), "%s", cp);
            required = True;
        } else if ((cp = getenv("HOME")) != NULL) {
            snprintf(xserverrcbuf, sizeof(xserverrcbuf),
                     "%s/%s", cp, XSERVERRC);
        }
        if (xserverrcbuf[0]) {
            if (access(xserverrcbuf, F_OK) == 0) {
                server += start_of_server_args - 1;
                server[0] = xserverrcbuf;
            } else if (required) {
                Error("warning, no server init file \"%s\"", xserverrcbuf);
            }
        }
    }

    /*
     * Start the server and client.
     */
    signal(SIGCHLD, SIG_DFL);    /* Insurance */

    /* Let those signal interrupt the wait() call in the main loop */
    memset(&sa, 0, sizeof sa);
    sa.sa_handler = sigCatch;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;    /* do not set SA_RESTART */

    sigaction(SIGTERM, &sa, NULL);
    sigaction(SIGQUIT, &sa, NULL);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGHUP, &sa, NULL);
    sigaction(SIGPIPE, &sa, NULL);

    memset(&si, 0, sizeof(si));
    si.sa_handler = sigIgnore;
    sigemptyset(&si.sa_mask);
    si.sa_flags = SA_RESTART;

    sigaction(SIGALRM, &si, NULL);
    sigaction(SIGUSR1, &si, NULL);

#ifdef __APPLE__
#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
    vt = vproc_transaction_begin(NULL);
#endif
#endif

    if (startServer(server) > 0
        && startClient(client) > 0) {
        pid = -1;
        while (pid != clientpid && pid != serverpid
               && gotSignal == 0
            )
            pid = wait(NULL);
    }

#ifdef __APPLE__
#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
    vproc_transaction_end(NULL, vt);
#endif
#endif

    signal(SIGTERM, SIG_IGN);
    signal(SIGQUIT, SIG_IGN);
    signal(SIGINT, SIG_IGN);
    signal(SIGHUP, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);

    shutdown();

    if (gotSignal != 0) {
        Errorx("unexpected signal %d", gotSignal);
        exit(EXIT_FAILURE);
    }

    if (serverpid < 0)
        Fatalx("server error");
    if (clientpid < 0)
        Fatalx("client error");
    exit(EXIT_SUCCESS);
}
Пример #19
0
int
main (int ac, char *ag[])
{
  int index;
  Queue < Server * >server;
  Server *s;
  Layer2Interface *l2;
  Layer3 *l3;
#ifdef HAVE_EIBNETIPSERVER
  EIBnetServer *serv = 0;
#endif

  memset (&arg, 0, sizeof (arg));
  arg.addr = 0x0001;
  arg.errorlevel = LEVEL_WARNING;

  argp_parse (&argp, ac, ag, 0, &index, &arg);
  if (index > ac - 1)
    die ("url expected");
  if (index < ac - 1)
    die ("unexpected parameter");

  if (arg.port == 0 && arg.name == 0 && arg.serverip == 0)
    die ("No listen-address given");

  signal (SIGPIPE, SIG_IGN);
  pth_init ();

  Trace t;
  t.SetTraceLevel (arg.tracelevel);
  t.SetErrorLevel (arg.errorlevel);

  /*
  if (getuid () == 0)
    ERRORPRINTF (&t, 0x37000001, 0, "EIBD should not run as root");
  */

  if(arg.eibnetname)
  {
      if(arg.eibnetname[0] == '=')
          arg.eibnetname++;
      if(strlen(arg.eibnetname) >= 30)
          die("EIBnetServer/IP name can't be longer then 30 char");
  }

  if (arg.daemon)
    {
      int fd = open (arg.daemon, O_WRONLY | O_APPEND | O_CREAT, FILE_MODE);
      if (fd == -1)
	die ("Can not open file %s", arg.daemon);
      int i = fork ();
      if (i < 0)
	die ("fork failed");
      if (i > 0)
	exit (0);
      close (1);
      close (2);
      close (0);
      dup2 (fd, 1);
      dup2 (fd, 2);
      close (fd);
      setsid ();
    }


  FILE *pidf;
  if (arg.pidfile)
    if ((pidf = fopen (arg.pidfile, "w")) != NULL)
      {
	fprintf (pidf, "%d", getpid ());
	fclose (pidf);
      }

  l2 = Create (ag[index], arg.backendflags, &t);
  if (!l2 || !l2->init ())
    die ("initialisation of the backend failed");
  l3 = new Layer3 (l2, &t);
  if (arg.port)
    {
      s = new InetServer (l3, &t, arg.port);
      if (!s->init ())
    die ("initialisation of the knxd inet protocol failed");
      server.put (s);
    }
  if (arg.name)
    {
      s = new LocalServer (l3, &t, arg.name);
      if (!s->init ())
	die ("initialisation of the knxd unix protocol failed");
      server.put (s);
    }
#ifdef HAVE_EIBNETIPSERVER
  serv = startServer (l3, &t, arg.eibnetname);
#endif
#ifdef HAVE_GROUPCACHE
  if (!CreateGroupCache (l3, &t, arg.groupcache))
    die ("initialisation of the group cache failed");
#endif

  signal (SIGINT, SIG_IGN);
  signal (SIGTERM, SIG_IGN);

  int sig;
  do
    {
      sigset_t t1;
      sigemptyset (&t1);
      sigaddset (&t1, SIGINT);
      sigaddset (&t1, SIGHUP);
      sigaddset (&t1, SIGTERM);

      pth_sigwait (&t1, &sig);

      if (sig == SIGHUP && arg.daemon)
	{
	  int fd =
	    open (arg.daemon, O_WRONLY | O_APPEND | O_CREAT, FILE_MODE);
	  if (fd == -1)
	    {
	      ERRORPRINTF (&t, 0x27000002, 0, "can't open log file %s",
			   arg.daemon);
	      continue;
	    }
	  close (1);
	  close (2);
	  dup2 (fd, 1);
	  dup2 (fd, 2);
	  close (fd);
	}

    }
  while (sig == SIGHUP);

  signal (SIGINT, SIG_DFL);
  signal (SIGTERM, SIG_DFL);
  while (!server.isempty ())
    delete server.get ();
#ifdef HAVE_EIBNETIPSERVER
  if (serv)
    delete serv;
#endif
#ifdef HAVE_GROUPCACHE
  DeleteGroupCache ();
#endif

  delete l3;
  if (Cleanup)
    Cleanup ();

  if (arg.pidfile)
    unlink (arg.pidfile);

  pth_exit (0);
  return 0;
}
Пример #20
0
void JobViewServer::init() {
  setupUi();
  readConfiguration();
  startServer();
}
Пример #21
0
void DialogManager::operator()() throw(Socket::ResolveException,Socket::WrongPortException)
{
    startServer();
}
Пример #22
0
void HttpServer::runOrExitProcess() {
  auto startupFailure = [] (const std::string& msg) {
    Logger::Error(msg);
    Logger::Error("Shutting down due to failure(s) to bind in "
                  "HttpServer::runAndExitProcess");
    // Logger flushes itself---we don't need to run any atexit handlers
    // (historically we've mostly just SEGV'd while trying) ...
    _Exit(1);
  };

  if (!RuntimeOption::InstanceId.empty()) {
    std::string msg = "Starting instance " + RuntimeOption::InstanceId;
    if (!RuntimeOption::DeploymentId.empty()) {
      msg += " from deployment " + RuntimeOption::DeploymentId;
    }
    Logger::Info(msg);
  }

  m_watchDog.start();

  if (RuntimeOption::ServerPort) {
    if (!startServer(true)) {
      startupFailure("Unable to start page server");
      not_reached();
    }
    Logger::Info("page server started");
  }

  StartTime = time(nullptr);

  if (RuntimeOption::AdminServerPort) {
    if (!startServer(false)) {
      startupFailure("Unable to start admin server");
      not_reached();
    }
    Logger::Info("admin server started");
  }

  for (unsigned int i = 0; i < m_satellites.size(); i++) {
    std::string name = m_satellites[i]->getName();
    try {
      m_satellites[i]->start();
      Logger::Info("satellite server %s started", name.c_str());
    } catch (Exception &e) {
      startupFailure(
        folly::format("Unable to start satellite server {}: {}",
                      name, e.getMessage()).str()
      );
      not_reached();
    }
  }

  if (!Eval::Debugger::StartServer()) {
    startupFailure("Unable to start debugger server");
    not_reached();
  } else if (RuntimeOption::EnableDebuggerServer) {
    Logger::Info("debugger server started");
  }

  InitFiniNode::ServerInit();

  {
    BootStats::mark("servers started");
    Logger::Info("all servers started");
    createPid();
    Lock lock(this);
    BootStats::done();
    // continously running until /stop is received on admin server, or
    // takeover is requested.
    while (!m_stopped) {
      wait();
    }
    if (m_stopReason) {
      Logger::Warning("Server stopping with reason: %s\n", m_stopReason);
    }
    // if we were killed, bail out immediately
    if (m_killed) {
      Logger::Info("page server killed");
      return;
    }
  }

  if (RuntimeOption::ServerPort) {
    Logger::Info("stopping page server");
    m_pageServer->stop();
  }
  onServerShutdown();

  EvictFileCache();

  waitForServers();
  m_watchDog.waitForEnd();
  playShutdownRequest(RuntimeOption::ServerCleanupRequest);
  hphp_process_exit();
  Logger::Info("all servers stopped");
}
Пример #23
0
void main(void){

	started = 0;
	receive = 1;

	next_move = DIR_STAY;

	mode = MODE_INIT;

	player_joined = 0;

	lcdClear();

	lcdPrintln("Up: server");
	lcdPrintln("Down: client");
	lcdPrintln("Enter: exit");
	
	lcdRefresh();

    int8_t priv = GLOBAL(privacy);
    GLOBAL(privacy) = 3;

	uint8_t btn;

	uint8_t cycles_wait;
	cycles_wait = 0;
	struct packet announce;
	do{
		btn = getInputRaw();

		if(mode == MODE_INIT){
			if(btn == BTN_UP){
				startServer();
			} else {
				if(btn == BTN_DOWN){
					startClient();
				}
			}
		}

		if(!started){
			if(mode == MODE_SERVER && !player_joined){
				memset((void*)&announce, 0, sizeof(announce));
				announce.gameid = gameid;
				announce.type = PKT_ANNOUNCE;
				memcpy(announce.c.announce.nick, GLOBAL(nickname), 16);
				announce.seq = 0;
				nrf_snd_pkt_crc(sizeof(announce), (uint8_t *)&announce);

				struct packet p;
				if(nrf_rcv_pkt_time(1000, sizeof(p), (uint8_t *)&p) == sizeof(p)){
					handle_packet(&p);
				}

			} else if (mode == MODE_CLIENT){
				struct packet p;
				if(nrf_rcv_pkt_time(100, sizeof(p), (uint8_t *)&p) == sizeof(p)){
					handle_packet(&p);
				}
			}
		} else {
			if(receive){
				struct packet p;
				if(nrf_rcv_pkt_time(50, sizeof(p), (uint8_t *)&p) == sizeof(p)){
					cycles_wait = 0;
					handle_packet(&p);
				} else {
					cycles_wait++;
				}

				if(cycles_wait >= 3){
					nrf_snd_pkt_crc(sizeof(latest_packet), (uint8_t *)&latest_packet);
					cycles_wait = 0;
				}
			} else {
				delayms(50);
			}

			next_move = btn;
		}
		
	}while(btn != BTN_ENTER);

	
	struct packet p;
	p.type = PKT_EXIT;
	for(uint8_t i = 0; i < 3; i++){
		delayms(50);
		nrf_snd_pkt_crc(sizeof(p), (uint8_t *)&p);
	}

	GLOBAL(privacy) = priv;
}
ServerWindow::ServerWindow(QWidget* parent)
    :QWidget(parent)
{
    setWindowTitle("Qt TasServer Ui");

    monitor = new ServerMonitor();

    statusButton = new QPushButton("Check status");
    stopButton = new QPushButton("Stop");
    startButton = new QPushButton("Start");
    resetButton =  new QPushButton ("Reset server");
    loadPluginsButton = new QPushButton("Load Plugins");
#ifdef Q_OS_SYMBIAN
    pluginButton = new QPushButton ("Enable tas");    
    autoStart = new QCheckBox("Autostart"); 
    autoStart->setTristate(false);
    if(monitor->autostartState()){
        autoStart->setCheckState(Qt::Checked);
    }
    connect(autoStart, SIGNAL(toggled(bool)), monitor, SLOT(setAutoStart(bool)));
#endif

    QLabel* stateLabel = new QLabel("Server state:");
    QLabel* versionLabel = new QLabel("Server version:");   
    QLabel* stateValue = new QLabel("Unknown");
    QLabel* versionValue = new QLabel(TAS_VERSION);


    QLabel* hostBindingLabel =  new QLabel("Server Address Binding:");
    anyBindRadioButton = new QRadioButton("Any");
    localBindRadioButton = new QRadioButton("Localhost");
    anyBindRadioButton->setDisabled(true);
    localBindRadioButton->setDisabled(true);

    connect(monitor, SIGNAL(serverState(const QString&)), stateValue, SLOT(setText(const QString&)));
    connect(monitor, SIGNAL(beginMonitor()), this, SLOT(disableButtons()));
    connect(monitor, SIGNAL(stopMonitor()), this, SLOT(enableButtons()));
    connect(monitor, SIGNAL(disableReBinding()), this, SLOT(disableRadioButtons()));
    connect(monitor, SIGNAL(enableReBinding(const QString&)), this, SLOT(enableRadioButtons(const QString&)));

    QTextEdit* editField = new QTextEdit();
    editField->setReadOnly(true);
    connect(monitor, SIGNAL(serverDebug(const QString&)), editField, SLOT(append(const QString&)));

    connect(startButton, SIGNAL(clicked()), editField, SLOT(clear()));
    connect(stopButton, SIGNAL(clicked()), editField, SLOT(clear()));
    connect(resetButton, SIGNAL(clicked()), editField, SLOT(clear()));
    connect(statusButton, SIGNAL(clicked()), editField, SLOT(clear()));
    connect(loadPluginsButton, SIGNAL(clicked()), editField, SLOT(clear()));


    connect(anyBindRadioButton, SIGNAL(clicked()), editField, SLOT(clear()));
    connect(localBindRadioButton, SIGNAL(clicked()), editField, SLOT(clear()));
    connect(anyBindRadioButton, SIGNAL(clicked()), monitor, SLOT(setAnyBinding()));
    connect(localBindRadioButton, SIGNAL(clicked()), monitor, SLOT(setLocalBinding()));


#ifdef Q_OS_SYMBIAN
    connect(pluginButton, SIGNAL(clicked()), editField, SLOT(clear()));
    connect(pluginButton, SIGNAL(clicked()), monitor, SLOT(enablePluginLoad()));
#endif

    connect(statusButton, SIGNAL(clicked()), monitor, SLOT(serverState()));    
    connect(stopButton, SIGNAL(clicked()), monitor, SLOT(stopServer()));
    connect(startButton, SIGNAL(clicked()), monitor, SLOT(startServer()));
    connect(resetButton, SIGNAL(clicked()), monitor, SLOT(restartServer()));    
    connect(loadPluginsButton, SIGNAL(clicked()),monitor, SLOT(loadPlugins()));

    QPushButton* quitButton = new QPushButton("Quit");
    connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit()));

    QGridLayout* mainLayout = new QGridLayout();
    mainLayout->addWidget(stateLabel, 0, 0, 1, 1);
    mainLayout->addWidget(stateValue, 0, 1, 1, 1);
    mainLayout->addWidget(versionLabel, 1, 0);
    mainLayout->addWidget(versionValue, 1, 1);

    // Server binding Radio
    mainLayout->addWidget(hostBindingLabel, 2, 0);
    mainLayout->addWidget(anyBindRadioButton, 2, 1);
    mainLayout->addWidget(localBindRadioButton, 3, 1);

    mainLayout->addWidget(editField, 4,0, 1, 2);
#ifdef Q_OS_SYMBIAN
    mainLayout->addWidget(statusButton, 5, 0);
    mainLayout->addWidget(pluginButton, 5, 1);
#else
    mainLayout->addWidget(statusButton, 5, 0);
    mainLayout->addWidget(loadPluginsButton, 5, 1);
#endif
    mainLayout->addWidget(stopButton, 6, 0);
    mainLayout->addWidget(startButton, 6, 1);
    mainLayout->addWidget(resetButton, 7, 0);
    mainLayout->addWidget(quitButton, 7, 1);
#ifdef Q_OS_SYMBIAN
    mainLayout->addWidget(autoStart, 8, 0);
    mainLayout->addWidget(loadPluginsButton, 8, 1);
#endif
    setLayout(mainLayout);     

//    QRect rect = qApp->desktop()->screenGeometry();    
//    if(rect.width() > 864)
//        setFixedSize(350,600);
//    else{
//        showFullScreen();    
//    }

}
Пример #25
0
int InitServer()
{
    char ErrBuff[256] = {0};
    FILE* fileLogTmp;
    //##############  CONFIGURATE SERVER  ###############
    
    // Read parameters from 'conf/httpd.conf' to list
    List *lstConf = initList();
    if (0 != getParamsFromFile("conf/httpd.conf", lstConf, '='))
    {
        puts("Could not read configuration file...");
        return 1;
    }
    // Apply parameters from list (or set to default, if they are absent)
    int port          = getParamInt(lstConf, "portListen",    80);
    int maxConn       = getParamInt(lstConf, "maxConnection", 100);
    char *logAccessPath = getParamS(lstConf, "logAccess",    "log/access.log");
    char *logErrorPath  = getParamS(lstConf, "logError",     "log/error.log");
    defaultPage         = getParamS(lstConf, "defaultPage",  "/index.htm");
    rootFolder          = getParamS(lstConf, "rootFolder",   "www/");
    char *interface     = getParamS(lstConf, "interfaceToListen", "");
    // Open new log files
    if ( initErrorLog(logErrorPath) == 0 )
    {
        return 1;
    }
    if ( !( fileLogAccess = fopen(logAccessPath, "a") ) )
    {
        snprintf(ErrBuff, sizeof(ErrBuff), "Could not open '%s'!", logAccessPath);
        puts(ErrBuff);
        logError(ErrBuff);
        return 1;
    }
    // Check if default page exists
    char *fullPath = malloc(strlen(rootFolder)+strlen(defaultPage)+1);
    strcpy(fullPath, rootFolder);
    strcat(fullPath, defaultPage);
    if (fileExists(fullPath) != 0)
    {
        snprintf(ErrBuff, sizeof(ErrBuff), 
            "Could not find default page following next path: '%s'!",
            fullPath);
        puts(ErrBuff);
        logError(ErrBuff);
    }
    // Free data with configuration from memory
    removeAll(lstConf);
    
    //#############  START SERVER  ###############

    struct sockaddr_in saddr;       // used for getting IP _
    socklen_t len = sizeof( saddr );// of incomming connection _
    char IP_Buff[INET_ADDRSTRLEN]; // defined in <netinet/in.h> .

    int listenSocket = 0, connSocket = 0;
    pid_t child_pid;
    
    // Try to start server
    listenSocket = startServer(interface, port, maxConn);

    if (listenSocket > 0)
    {
        #ifndef __DEBUG_MODE__
        logError("#Server started Successfully!");
        #endif
        printf("\n\nServer started Successfully!\n\n");
        //#############  MAIN PROCESSING LOOP  ###############
        while(1)
        {
            // Wait few second, if there's no connections - continue
            if (wait4Socket(listenSocket, ACCEPT_TIMEOUT) > 0)
            {
                connSocket = accept( listenSocket, ( struct sockaddr* )&saddr, &len );
                if ( listenSocket < 0 ) {
                    logError("Accept Error...");
                    break;
                }
                
                child_pid = fork ();
                if (child_pid == 0)     //####  child thread  ####
                {
                    #ifndef __DEBUG_MODE__
                    close (STDIN_FILENO);     //child don't need to print anything,
                    close (STDOUT_FILENO);    //  so close input/output streams
                    #endif
                    close (listenSocket);       //close a child-copy of listening port
                    
                    if ( inet_ntop( AF_INET, &saddr.sin_addr, IP_Buff, INET_ADDRSTRLEN ) == NULL )
                    {
                        logError("Can't convert IP addr");
                        close(connSocket);
                        exit(1);
                    }
                    procConn(IP_Buff, connSocket);
                    
                    exit (0);       // close child process
                }
                else if (child_pid > 0) // ####  parent thread  ####
                {
                    
                    close (connSocket);
                    #ifdef __DEBUG_MODE__
                    if (getComm() == 0)
                    {
                        break;
                    }
                    #endif
                }
                else
                    logError("Can't fork");     // if can't create child
            }
        }
        close(listenSocket);    // close parent listenSocket


        #ifndef __DEBUG_MODE__
        logError("#Server closed Successfully!");
        #endif
        printf("\n\nServer closed Successfully!\n\n");
        
        return 0;
    }
    logError("#Server was not started!");
    printf("\n\nServer was not started! See error.log to get more information!\n\n");
    return 1;
}
Пример #26
0
int main(void){
    startServer();
    return 0;
}
Пример #27
0
 virtual void SetUp() {
   startServer();
   connectClient();
 }
Пример #28
0
int attackResProtocol(char* backupserver1_host, char* backupserver2_host,
		char* backupserver3_host, char* backupserver4_host,
		char* backupserver_port, char* num_of_attack, char* num_of_pdcs,
		int num_attack, int sockfd, Logger* fLogger) {

	time_t now_time;
	struct tm * tm_info;
	char timebuffer[25];

	log_debug(fLogger,"Something wrong with the connection of old server. Disconnecting.");
	shutdown(sockfd, SHUT_RDWR);
    close(sockfd);

	log_debug(fLogger,"Attack Number %d", num_attack);

	char* backupserver_host;
	if (num_attack==1) {
		backupserver_host = backupserver1_host;
	}
	if (num_attack==2) {
		backupserver_host = backupserver2_host;
	}
	if (num_attack==3) {
		backupserver_host = backupserver3_host;
	}
	if (num_attack==4) {
		backupserver_host = backupserver4_host;
	}

	log_debug(fLogger,"Backup Server Host: %s", backupserver_host);

	if (atoi(num_of_attack) == num_attack) {
		//Strategy 1: run server source code in the fourth backup Client 4 VM background
		log_debug(fLogger, "This node itself is the next backup server");
		log_debug(fLogger,"Starting ADMM Server");
		startServer(num_of_pdcs, backupserver_port);
		log_debug(fLogger,"New ADMM Server started at PDC");
	}

	struct sockaddr_in new_serv_addr;
    memset(&new_serv_addr, '0', sizeof(new_serv_addr));
    new_serv_addr.sin_family = AF_INET;

    //Strategy 0&1: backup server or run a server side at client1
    // Create a socket and connection with predefined new server
    struct hostent *he1;
    struct in_addr **addr_list1;
    char* bkpsvr_ip;

    if ((he1 = gethostbyname(backupserver_host)) == NULL) {  // get the host info
		exit(1);
	}

	addr_list1 = (struct in_addr **)he1->h_addr_list;
	for(int i = 0; addr_list1[i] != NULL; i++) {
		bkpsvr_ip = inet_ntoa(*addr_list1[i]);
	}

	log_debug(fLogger, "Connecting to Backup Server");
	log_debug(fLogger, "Server Host: %s, IP: %s, Port:%s", backupserver_host, bkpsvr_ip, backupserver_port);

	new_serv_addr.sin_port = htons(atoi(backupserver_port));
	if(inet_pton(AF_INET, bkpsvr_ip, &new_serv_addr.sin_addr)<=0){
		log_error(fLogger,"inet_pton error occurred");
		return 1;
	}

	int new_sockfd;

    if((new_sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
    	log_error(fLogger,"Could not create socket.");
    	return 1;
    }
    log_debug(fLogger,"Socket created");

    while (1){
        if(connect(new_sockfd, (struct sockaddr *)&new_serv_addr, sizeof(new_serv_addr)) < 0){
        	//log_debug(fLogger,"Connect failed. Will try again.");
        	continue;
        } else {
        	log_debug(fLogger,"New TCP connection setup successfully.");
            break;
        }
    } //end-while

    return new_sockfd;
}
Пример #29
0
void HttpServer::run() {
  StartTime = time(0);

  m_watchDog.start();

  for (unsigned int i = 0; i < m_serviceThreads.size(); i++) {
    m_serviceThreads[i]->start();
  }
  for (unsigned int i = 0; i < m_serviceThreads.size(); i++) {
    m_serviceThreads[i]->waitForStarted();
  }

  if (RuntimeOption::ServerPort) {
    if (!startServer(true)) {
      Logger::Error("Unable to start page server");
      return;
    }
    Logger::Info("page server started");
  }

  if (RuntimeOption::AdminServerPort) {
    if (!startServer(false)) {
      Logger::Error("Unable to start admin server");
      abortServers();
      return;
    }
    Logger::Info("admin server started");
  }

  for (unsigned int i = 0; i < m_satellites.size(); i++) {
    string name = m_satellites[i]->getName();
    try {
      m_satellites[i]->start();
      Logger::Info("satellite server %s started", name.c_str());
    } catch (Exception &e) {
      Logger::Error("Unable to start satellite server %s: %s",
                    name.c_str(), e.getMessage().c_str());
      abortServers();
      return;
    }
  }

  if (!Eval::Debugger::StartServer()) {
    Logger::Error("Unable to start debugger server");
    abortServers();
    return;
  } else if (RuntimeOption::EnableDebuggerServer) {
    Logger::Info("debugger server started");
  }

  for (InitFiniNode *in = extra_server_init; in; in = in->next) {
    in->func();
  }

  {
    Logger::Info("all servers started");
    createPid();
    Lock lock(this);
    // continously running until /stop is received on admin server
    while (!m_stopped) {
      wait();
    }
    if (m_stopReason) {
      Logger::Warning("Server stopping with reason: %s\n", m_stopReason);
    }
    removePid();
    Logger::Info("page server stopped");
  }

  onServerShutdown(); // dangling server already started here
  time_t t0 = time(0);
  if (RuntimeOption::ServerPort) {
    m_pageServer->stop();
  }
  time_t t1 = time(0);
  if (!m_danglings.empty() && RuntimeOption::ServerDanglingWait > 0) {
    int elapsed = t1 - t0;
    if (RuntimeOption::ServerDanglingWait > elapsed) {
      sleep(RuntimeOption::ServerDanglingWait - elapsed);
    }
  }

  for (unsigned int i = 0; i < m_danglings.size(); i++) {
    m_danglings[i]->stop();
    Logger::Info("dangling server %s stopped",
                 m_danglings[i]->getName().c_str());
  }

  for (unsigned int i = 0; i < m_serviceThreads.size(); i++) {
    m_serviceThreads[i]->notifyStopped();
  }
  for (unsigned int i = 0; i < m_serviceThreads.size(); i++) {
    m_serviceThreads[i]->waitForEnd();
  }

  hphp_process_exit();
  m_watchDog.waitForEnd();
  Logger::Info("all servers stopped");
}
Пример #30
0
int main(int argc, char* argv[])
{
    struct sockaddr_in clientaddr;
    socklen_t addrlen;
    char c;
    int tmp=0;
    while(tmp<5){
    	pthread_mutex_init(&lock[tmp],NULL);
    	pthread_mutex_lock(&lock[tmp]);
    	createThread(tmp);
    	tmp++;
    }
    //дефолтные значения
    char PORT[6];
    ROOT = getenv("PWD");//возвращает значение переменной окружения
    strcpy(PORT,"10000"); //копирование из второй строки в первую. возвращает указатель на результирующую строку

    int slot=0;

    //парсим аргументы
    while ((c = getopt (argc, argv, "p:r:h")) != -1)
        switch (c)
        {
            case 'r':
                ROOT = malloc(strlen(optarg));//распределяет байты в памяти и возвращает указатель на память. strlen - длина строки, optarg - строковое значение параметра
                strcpy(ROOT,optarg);
                break;
            case 'p':
                strcpy(PORT,optarg);
                break;
	    case 'h':
		helping();
            case '?':
                fprintf(stderr,"Wrong arguments given!!!\n");
                exit(1);
            default:
                exit(1);
        }
    
    //установка всех элементов в -1
    int i;
    for (i=0; i<CLIENTMAX; i++)
        clients[i]=-1;
    startServer(PORT);
    printf("Server started at port no. %s%s%s with root directory as %s%s%s\n","\033[92m",PORT,"\033[0m","\033[92m",ROOT,"\033[0m");
    int j=0;
    // прием соединений
    while (1)
    {
        addrlen = sizeof(clientaddr);
        clients[slot] = accept (listenfd, (struct sockaddr *) &clientaddr, &addrlen);//принять соединение на сокете (сокет, адрес другой стороны, длина адреса в байтах)
        if(j>4)
		{
			j=0;
            int k=0;
            int coeff=slot/5;
            while(k<5)
			{
				if(pthread_mutex_trylock(&lock[k])==0)
					createThread(k+5*coeff);
                k++;
			}
		}
        if (clients[slot]<0)
            error ("accept() error");
        else
        {
                pthread_mutex_unlock(&lock[j]);        
        }
		j++;
        while (clients[slot]!=-1) slot = (slot+1)%CLIENTMAX;
    }
    return 0;
}