Пример #1
0
static void start_poll_test(void) {
  int i, r;

#ifdef _WIN32
  {
    struct WSAData wsa_data;
    int r = WSAStartup(MAKEWORD(2, 2), &wsa_data);
    ASSERT(r == 0);
  }
#endif

  start_server();

  for (i = 0; i < NUM_CLIENTS; i++)
    start_client();

  r = uv_run(uv_default_loop(), UV_RUN_DEFAULT);
  ASSERT(r == 0);

  /* Assert that at most five percent of the writable wakeups was spurious. */
  ASSERT(spurious_writable_wakeups == 0 ||
         (valid_writable_wakeups + spurious_writable_wakeups) /
         spurious_writable_wakeups > 20);

  ASSERT(closed_connections == NUM_CLIENTS * 2);
  ASSERT(disconnects == NUM_CLIENTS * 2);

  MAKE_VALGRIND_HAPPY();
}
Пример #2
0
int main(int argc, char **argv) {
    int c;
    int option_index = 0;
    int count = -1;
    int server = 0;
    static struct option long_options[] = {
        {"count", required_argument, 0, 'c'},
        {"server", no_argument, 0, 's'},
        {0, 0, 0, 0 }
    };
    while (1) {
        c = getopt_long(argc, argv, "c:s", long_options, &option_index);
        if (c == -1)
            break;
        switch (c) {
        case 'c':
            count = atoi(optarg);
            break;
        case 's':
            server = 1;
            break;
        }
    }
    if (server) start_server();
    else start_client(count);
    return 0;
}
Пример #3
0
	//Function that reset the network when the scene
	//is restarted
	void Network::reset() {
		if (has_server && server)
			start_server();
		if (has_client && client)
			start_client();
		NetId::last_id = 0;

	}
Пример #4
0
int main (int argc,char **argv){
   struct sockaddr_in server;
   struct fgetinfo    *p1;
   struct finfo       p4;
   char               buffer[10000];
   FILE *foutfd;
   
   char host[1000],fin[FILENAME_MAX],fout[FILENAME_MAX];
   int sock,port,connected,retval;
 
   parse(argc,argv,host,&port,fin,fout);
   
   /* PRINT PARSED ARGUMENTS */
   printf("Port %i<--\n",port);
   printf("Server %s<--\n",host);

   start_client(&sock,&server,port,host);
   printf("Starting communication\n\n");
   p1=get_info(fin);

   // Try to open out file
   if((foutfd=(FILE *)fopen(fout,"wb"))==NULL){
      printf("Out file could't be created or truncated for writing\n");
      exit(1);
   }
   
   connected=0;
   while (connected<3){
      connected++;
      send_buf(sock,&server,p1,sizeof(*p1));
      print_fgetinfo(*p1);
      
      if(receive(sock,buffer,sizeof(buffer))==0){
         memcpy(&p4,buffer,sizeof(p4));
         if(!check_finfo(p4)){
            connected=4;
            print_finfo(p4);
            if (p4.file_exist==1){
               // Start transfer
               retval=transfer(sock,&server,p4.file_id,foutfd,p4.file_size);
               fclose(foutfd);
               // Show transfer result
               exit(retval);
            }
            else{
               printf("\nERROR: Requested file does not exist on server\n\n");
               exit(1);
            }
         }
      }
   }
   if (connected==3){
      printf("\nERROR: Server not responding\n\n");
      exit(1);
   }
   exit (0);
}
Пример #5
0
/**
 *  \brief USB manager's client side interfacing. Functions in this 
 *         file acts as glue to the client side call. 
 */
int connect_to_usb_manager(void *args)
{
    printf("\n\n\n\n Thread entry -- %s", __func__);
    struct chips_context *context = chips_get_context();
    context->init();
    printf("\n USB_DRIVER: Context init at usb_manager client"
           "Trying to connect\n ");
    start_client(context);
    return 0;
}
Пример #6
0
int
main(int argc, char * const argv[]) {
  if (argc != 3) {
    fprintf(stderr, "Usage: \n");
    fprintf(stderr, "  %s ciphersuite certificate\n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, " - `ciphersuite` is the name of cipher suite to use. Use\n");
    fprintf(stderr, "   `openssl ciphers` to choose one.\n");
    fprintf(stderr, "\n");
    fprintf(stderr, " - `certificate` is the name of the file containing\n");
    fprintf(stderr, "   the certificate, the key and appropriate additional parameters.\n");
    return 1;
  }

  const char *ciphersuite = argv[1];
  const char *certificate = argv[2];

  start("Initialize OpenSSL library");
  SSL_load_error_strings();
  SSL_library_init();
  if (!(mutex_buf = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t))))
    fail("Unable to allocate memory for mutex");
  for (int i = 0;  i < CRYPTO_num_locks();  i++)
    pthread_mutex_init(&mutex_buf[i], NULL);
  CRYPTO_set_id_callback(id_function);
  CRYPTO_set_locking_callback(locking_function);

  pthread_t client, server;
  start("Prepare client and server");
  if (socketpair(AF_UNIX, SOCK_STREAM, 0, clientserver))
    fail("Unable to get a socket pair for client/server communication:\n%m");
  server = start_server(ciphersuite, certificate);
  client = start_client(ciphersuite);

  struct result *client_result, *server_result;
  start("Waiting for client to finish");
  if (pthread_join(client, (void **)&client_result))
    fail("Unable to join client thread");
  start("Waiting for server to finish");
  if (pthread_join(server, (void **)&server_result))
    fail("Unable to join server thread");

  end("Got the following results:\n"
      "Handshakes from client: %d\n"
      "User CPU time in client: %4ld.%03ld\n"
      "Handshakes from server: %d\n"
      "User CPU time in server: %4ld.%03ld\n"
      "Ratio: %.2f %%",
      client_result->handshakes,
      client_result->cpu.tv_sec, client_result->cpu.tv_nsec / 1000000,
      server_result->handshakes,
      server_result->cpu.tv_sec, server_result->cpu.tv_nsec / 1000000,
      (server_result->cpu.tv_sec * 1000. + server_result->cpu.tv_nsec / 1000000.) * 100. /
      (client_result->cpu.tv_sec * 1000. + client_result->cpu.tv_nsec / 1000000.));
}
int
main(int argc, char **argv) {
	in_addr_t local_addr;
	uint16_t port;
	uint16_t istreams, ostreams;
	uint16_t max_attemps, max_timeout;
	int c;

	local_addr = INADDR_ANY;
	port = 0;
	istreams = 0;
	ostreams = 0;
	max_attemps = 0;
	max_timeout = 0;

	while ((c = getopt(argc, argv, "hL:i:o:N:p:T:")) != -1) {
		switch(c) {
			case 'h':
				fprintf(stderr, "%s", Usage);
				return 0;
				break;
			case 'i':
				istreams = atoi(optarg);
				break;
			case 'L':
				local_addr = inet_addr(optarg);
				break;
			case 'N':
				max_attemps = atoi(optarg);
				break;
			case 'o':
				ostreams = atoi(optarg);
				break;
			case 'p':
				port = atoi(optarg);
				break;
			case 'T':
				max_timeout = atoi(optarg) * 1000;
				break;
			default:
				fprintf(stderr, "%s", Usage);
				return -1;
		}
	}

	if (optind == argc) {
		start_server(local_addr, istreams, ostreams);
	} else {
		start_client(local_addr, port, inet_addr(argv[optind]), atoi(argv[optind+1]),
		             istreams, ostreams, max_attemps, max_timeout);
	}

	return 0;
}
Пример #8
0
int start(int argc, char *argv[]) {
	
	printf(".:: TCP PING ::.\n");
	if(!processArguments(argc, argv)) return -1;
	
	if(mode == SERVER) {
		start_server(CONFIG_LISENT_IFACE, port, CONFIG_MAX_CLIENT);
	} else if(mode == CLIENT) {
		start_client(ip_dst,port,msg_count,msg_size);
	}
	
	return 0;
}
Пример #9
0
/// seriously? you are reading what main is about? go away!
int main(int argc, char *argv[]) {
    char const* dev;

    sender_address = 1;
    destination_address = 254;

    if (argc < 2) {
        LOG_WARN("Running in stdin/stdout mode. Expecting two different FIFOs (or pipes) to read/write.");
        LOG_INFO("You may run for example:");
        LOG_INFO("mkfifo \"$MYFIFO\" && ./client < \"$MYFIFO\" | ./gateway - eth0 > \"$MYFIFO\"; [ -p \"$MYFIFO\" ] && rm \"$MYFIFO\"");
        dev = 0; //special meaning
    } else {
        dev = argv[1];
    }

    start_client(dev);
    return 0;
}
Пример #10
0
int main(int argc, char *argv[], char *envp[]) {
    /* avoid SIGPIPE */
    signal(SIGPIPE,SIG_IGN);
    
    /* avoid erroneous signal from other mbbsd */
    signal(SIGUSR1,SIG_IGN);
    signal(SIGUSR2,SIG_IGN);
    
    /* check if invoked as "bbs" */
    if(argc == 3)
	shell_login(argc,argv,envp);
    else
    	daemon_login(argc,argv,envp);
    
    nice(2);	/*  Ptt: lower priority */
    login_start_time = time(0);
    start_client();
    return 0;
}
Пример #11
0
/* 主函数 */
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    int i;
    int r;
    int port = 8888;
    bool server_mode =1;
    char *addr =NULL;
    port = DEFAULT_PORT;
    server_mode = 0;
    addr = "172.20.9.59";
    /* 对命令行参数进行分析 */
    for (i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-s") == 0) { /* 如果是 -s */
            server_mode = 1; /* 说明要以服务器方式启动 */
        } else if (strcmp(argv[i], "-p") == 0) { /* 如果是 -p */
            server_mode = 0;  /* 说明要以client方式启动 */
            i++; /* 下一个参数 */
            if (i >= argc) {
                printf("Error: must specify port number!\n");
                return -1;
            }
            port = atoi(argv[i]); /* 是端口号 */
            if (port == 0) {
                printf("Error: wrong port number!\n");
                return -1;
            }
        } else { /* 否则 */
            addr = argv[i]; /* 是 IP 地址 */
        }
    }
    if (server_mode) {
        r = start_server(port); /* 启动服务器 */
    } else {
        r = start_client(addr, port); /* 启动客户端 */
    }
//    return r;


    
    return a.exec();
}
Пример #12
0
/* Check that the server sends back the same byte that the client sent.
   If MAX_REQUESTS have been reached, exit. Otherwise, start another client. */
static void
client_read_cb(struct bufferevent *bev, void *ctx)
{
	unsigned char tmp;
	struct event_base *base = bufferevent_get_base(bev);

	bufferevent_read(bev, &tmp, 1);
	if (tmp != 'A') {
		puts("Incorrect data received!");
		exit(2);
	}
	bufferevent_free(bev);

	num_requests++;
	if (num_requests == MAX_REQUESTS) {
		event_base_loopbreak(base);
	} else {
		start_client(base);
	}
}
Пример #13
0
/* Start the server listening on a random port and start the first client. */
static void
start_loop(void)
{
	struct event_base *base;
	struct evconnlistener *listener;
	struct sockaddr_storage ss;
	ev_socklen_t socklen = sizeof(ss);
	evutil_socket_t fd;

	base = event_base_new();
	if (base == NULL) {
		puts("Could not open event base!");
		exit(1);
	}

	listener = evconnlistener_new_bind(base, listener_accept_cb, NULL,
	    LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
	    -1, (struct sockaddr *)&saddr, sizeof(saddr));
	if (listener == NULL) {
		my_perror("Could not create listener!");
		exit(1);
	}
	fd = evconnlistener_get_fd(listener);
	if (fd < 0) {
		puts("Couldn't get fd from listener");
		exit(1);
	}
	if (getsockname(fd, (struct sockaddr *)&ss, &socklen) < 0) {
		my_perror("getsockname()");
		exit(1);
	}
	memcpy(&saddr, &ss, sizeof(saddr));
	if (saddr.sin_family != AF_INET) {
		puts("AF mismatch from getsockname().");
		exit(1);
	}

	start_client(base);

	event_base_dispatch(base);
}
Пример #14
0
int parse_args(int argc, char* argv[]) {
    if(argc < 2) {
        fprintf(stderr,"Take an arguments or use --help\n");
        return argc;
    }
    bool hs=true;
    for(int i = 1; i < argc; i++) {
        if(argv[i][0]=='-') {
            if((!strcmp(argv[i], "--help")||!strcmp(argv[i],"-h"))&&hs) {
                show_help();
                hs=!hs;
            }
            if(!strcmp(argv[i], "-s")) {
                fprintf(stdout, "Start as server\n");
                start_server(argv[i++]);
            }
            if(!strcmp(argv[i], "--server-cfg")) {
                fprintf(stdout, "Let's configure a server!\n");
                server_cfg(argv[i++]);
            }
            if(!strcmp(argv[i], "-c")) {
                fprintf(stdout, "Start as client\n");
                start_client(argv[i++]);
            }
            if(!strcmp(argv[i], "-r")) {
                fprintf(stdout, "Start a registration\n");
                registration(argv[i++]);
            }
        }
        else {
            fprintf(stderr, "Wrong arguments\n");
            if(hs)
                show_help();
            return 0;
        }
    }
    return 0;
}
Пример #15
0
int main(int argc, char *argv[])
{
	if (signal(SIGINT, sig_handler) == SIG_ERR)
	  printf("\ncan't catch SIGINT\n");
	// check command line args.

//		if (argc == 2)
//		{
//			// then run in routing table mode
//			buildrt(argv[1]);
//			exit(0);
//		}

	if (argc == 2)
	{
		// then running in server mode
		printf("Running in server mode with port %s\n", argv[1]);
		strcpy(port, argv[1]);
		start_server(port);
	}
	else if (argc < 4)
	{
		printf("usage : %s <client name> <server IP> <server port> \n", argv[0]);
		exit(1);
	}

	if (argc == 4)
	{
		printf("Running as client:\n");
		strcpy(clientName, argv[1]);
		strcpy(serverIp, argv[2]);
		strcpy(serverPort, argv[3]);
		start_client(clientName, serverIp, serverPort);
	}
	return 0;


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

    if ((argc >= 2) && (strcmp(argv[1], "client") == 0)) {
        start_client();
    } else if ((argc >= 2) && (strcmp(argv[1], "server") == 0)) {
        start_server();
    } else {
        printf("usage: %s client|server\n", argv[0]);
        return EXIT_FAILURE;
    }

    struct waitset *ws = get_default_waitset();
    while (1) {
        err = event_dispatch(ws);
        if (err_is_fail(err)) {
            DEBUG_ERR(err, "in event_dispatch");
            break;
        }
    }

    return EXIT_FAILURE;
}
Пример #17
0
/* 主模块 */
int main(int argc, char *argv[])
{
	int i;
	int r;
	int port;
	int server_mode;
	char *addr;
	port = DEFAULT_PORT;
	server_mode = 0;
	addr = "202.206.219.143";
	/* 对命令行参数进行分析 */
	for (i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-s") == 0) { /* 如果是 -s */
			server_mode = 1; /* 说明要以服务器方式启动 */
		} else if (strcmp(argv[i], "-p") == 0) { /* 如果是 -p */
			i++; /* 下一个参数 */
			if (i >= argc) {
				printf("Error: must specify port number!\n");
				return -1;
			}
			port = atoi(argv[i]); /* 是端口号 */
			if (port == 0) {
				printf("Error: wrong port number!\n");
				return -1;
			}
		} else { /* 否则 */
			addr = argv[i]; /* 是 IP 地址 */
		}
	}
	if (server_mode) {
		r = start_server(port); /* 启动服务器 */
	} else {
		r = start_client(addr, port); /* 启动客户端 */
	}
	return r;
}
Пример #18
0
////////////////////////////////////////////////////////////////////////////////
// Main
int main()
{
	start_server();
	start_client();
	return 0;
}
Пример #19
0
void start_client(char *srv, int port)
{
    int socket_d, ret;
    socklen_t len_inet;
    struct sigaction sa;
    struct sockaddr_in in_addr;
    char buf[bufsize];
    ssize_t reads;
    struct timespec rem;
    struct timespec req = { .tv_sec = 0,
               .tv_nsec = 1492000
    };

    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    sa.sa_handler = chld_reaper;
    if (sigaction(SIGCHLD, &sa, NULL) == -1)
        oops("error from sigaction()");

    socket_d = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_d == -1)
        oops("error from socket()");

    len_inet = sizeof(struct sockaddr_in);

    memset(&in_addr, 0, len_inet);
    in_addr.sin_family = AF_INET;
    in_addr.sin_port = htons(port);
    in_addr.sin_addr.s_addr = inet_addr(srv);

    if (connect(socket_d, (struct sockaddr *)&in_addr, len_inet) == -1)
        oops("error from connect()");

    switch(fork()) {
    case -1:
        oops("error from fork()");

    case 0:  /* child -- read server's response */
        for (;;) {
            reads = readn(socket_d, buf, bufsize);
            if (reads <= 0)
                break;

            printf("%.*s", (int) reads, buf);
        }
        exit(EXIT_SUCCESS);

    default: /* parent -- write stdin to socket */
        for (;;) {
            req.tv_nsec++;
            if (req.tv_nsec >= 14920000)
                req.tv_nsec = 1492000;

            reads = read(STDIN_FILENO, buf, bufsize);
            if (reads <= 0)
                break;

            /* insert some sleep */
retry:
            ret = nanosleep(&req, &rem);
            if (ret) {
                if (errno == EINTR) {
                    req.tv_sec = rem.tv_sec;
                    req.tv_nsec = rem.tv_nsec;
                    goto retry;
                }
                syslog(LOG_ERR, "nanosleep() failed: %s",
                       strerror(errno));
            }

            writen(socket_d, buf, bufsize);

        }
        exit(EXIT_SUCCESS);
    }
}

int main(int argc, char *argv[])
{
    int next_opt, mode = 0;
    char *server = NULL;
    const char *short_opts = "hsc:p:b:";
    const struct option long_opts[] = {
        {"help", 0, NULL, 'h'},
        {"server", 0, NULL, 's'},
        {"client", 1, NULL, 'c'},
        {"port", 1, NULL, 'p'},
        {"bufsz", 1, NULL, 'b'},
        {NULL, 0, NULL, 0}
    } ;

    int port_num = 9999;
    prg_name = argv[0];

    do {
        next_opt = getopt_long(argc, argv, short_opts, long_opts, NULL);
        switch (next_opt) {
        case 'h':
            print_usage(stdout, 0);

        case 's':
            mode += 1;
            break;

        case 'c':
            mode += 2;
            server = optarg;
            break;

        case 'p':
            port_num = atoi(optarg);
            break;

        case 'b':
            bufsize = atoi(optarg);
            break;

        case '?':
            print_usage(stderr, 1);

        case -1:
            break;

        default:
            abort();
        }
    } while (next_opt != -1);

    if (argc == 1)
        print_usage(stderr, 2);

    if (mode == 0 || mode > 2)
        oops("Ok, I cannot realize what you want now...");

    switch (mode) {
    case 1: /* server mode */
        if (deamonize() == -1)
            oops("failed to become a deamon.");

        start_server(port_num);
        break;
    case 2: /* client mode */
        start_client(server, port_num);
        break;
    }

    return 0;
}
Пример #20
0
int main(int argc , char *argv[]) {
  /* Get program name. */
  char *progname = strrchr(argv[0], '/');
  if (progname)
    progname++;
  else
    progname = argv[0];

  /* Possible command-line arguments. */
  bool is_server = 0;
  bool is_client = 0;
  char *server = NULL;
  char *port_str = NULL;
  int port = -1;
  int window = 1;
  seed = time(NULL);
  test_debug_on = false;
  lab5_mode = false;
  struct option o[] = {
    { "debug", no_argument, NULL, 'd' },

    { "server", no_argument, NULL, 's' },
    { "client", required_argument, NULL, 'c' },
    { "port", required_argument, NULL, 'p' },
    { "window", required_argument, NULL, 'w' },

    { "seed", required_argument, NULL, 'e'},
    { "drop", required_argument, NULL, 'r' },
    { "corrupt", required_argument, NULL, 't' },
    { "delay", required_argument, NULL, 'y' },
    { "duplicate", required_argument, NULL, 'q' },
    { "logging", no_argument, NULL, 'l' },
    { "lab5", no_argument, NULL, 'f' },
    { NULL, 0, NULL, 0 }
  };

  /* Parse command-line arguments. */
  int opt;
  while ((opt = getopt_long(argc, argv, "dsc:p:w:r:t:y:q:lzf", o, NULL)) != -1) {
    switch (opt) {
    /* Debug statements on. */
    case 'd':
      DEBUG = true;
      break;
    /* Run as server. */
    case 's':
      is_server = true;
      break;
    /* Run as client and connect to a specified server. */
    case 'c':
      is_client = true;
      server = optarg;
      break;
    /* Port to run on. */
    case 'p':
      port = atoi(optarg);
      port_str = optarg;
      break;
    /* Window size. */
    case 'w':
      window = atoi(optarg);
      break;
    /* Seed for unreliability. */
    case 'e':
      seed = atoi(optarg);
      break;
    /* Segment drop. */
    case 'r':
      opt_drop = atoi(optarg);
      break;
    /* Segment corruption. */
    case 't':
      opt_corrupt = atoi(optarg);
      break;
    /* Segment delay. */
    case 'y':
      opt_delay = atoi(optarg);
      break;
    /* Segment duplicate. */
    case 'q':
      opt_duplicate = atoi(optarg);
      break;
    /* Turn logging on. */
    case 'l':
      log_file = 0;
      break;
    /* Turn logging data off for tester. */
    case 'z':
      test_debug_on = true;
      break;
    /* Lab 5 mode for handling FINs. */
    case 'f':
      lab5_mode = true;
      break;
    default:
      usage(progname);
      break;
    }
  }

  /* Seed RNG. */
  srand(seed);

  /* Validate arguments. */
  if ((is_client && is_server) || (!is_client && !is_server) || port <= 0) {
    usage(progname);
  }

  /* Construct log file if logging is turned on. Don't create a file if not
     logging data, since that is only used for testing purposes. */
  if (log_file == 0) {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    char log_filename[40];
    memset(log_filename, 0, 40);
    snprintf(log_filename, sizeof(log_filename), "%d-%d.csv", (int) tv.tv_sec,
             port);
    log_file = open(log_filename, O_CREAT | O_TRUNC | O_WRONLY, 0666);
    write_log_header(log_file);
  }

  /* Global configuration. */
  struct config cc;
  config = &cc;

  /* CTCP config for students. */
  static ctcp_config_t cfg;
  ctcp_cfg = &cfg;
  cfg.recv_window = window * MAX_SEG_DATA_SIZE;
  cfg.send_window = window * MAX_SEG_DATA_SIZE;
  cfg.timer = TIMER_INTERVAL;
  cfg.rt_timeout = RT_INTERVAL;

  /* Used for polling later. */
  struct pollfd _events[NUM_POLL + MAX_NUM_CLIENTS];
  memset(_events, 0, sizeof(struct pollfd) * (NUM_POLL + MAX_NUM_CLIENTS));
  events = _events;

  /* Start client/server. */
  if (is_client) {
    if (start_client(server, port_str) < 0) {
      fprintf(stderr, "[ERROR] Client terminated\n");
      return 1;
    }
  }
  else if (is_server) {
    SERVER = true;
    if (start_server(port_str, argc, argv) < 0) {
      fprintf(stderr, "[ERROR] Server terminated\n");
      return 1;
    }
  }
  return 0;
}
Пример #21
0
static void APP_main()
{
   ip_connected = false;
   kaa_started = false;

   kaa_error_t kaa_error = KAA_ERR_NONE;
   { //Used to limit kaa_props visibility, it creates on stack and release once is used
       kaa_client_props_t kaa_props;
       kaa_props.max_update_time = 2;
       kaa_error = kaa_client_create(&kaa_client, &kaa_props);
       if (kaa_error) {
           sndc_printf("Error %d initializing Kaa client \n",kaa_error);
           return;
       }
   }

   kaa_list_t *zones = kaa_list_create();
   int i = 0;
   for(; i < LIGHT_ZONES_COUNT; ++i) {
       sndc_io_setMode(light_zones[i], IO_MODE_OUTPUT);
       sndc_io_write(light_zones[i], LIGHT_OFF);
       int32_t *zone_id = (int32_t *) KAA_MALLOC(sizeof(int32_t));
       *zone_id = i;
       kaa_list_push_front(zones, zone_id);
   }
   kaa_profile_street_lights_profile_t *profile = kaa_profile_street_lights_profile_create();
   profile->light_zones = zones;
   kaa_profile_manager_update_profile(kaa_client_get_context(kaa_client)->profile_manager, profile);
   profile->destroy(profile);

   /**
    * Configuration example, below is how to configure and read default configuration values
    */
   kaa_configuration_root_receiver_t receiver = { NULL, &kaa_on_configuration_updated };
   kaa_error = kaa_configuration_manager_set_root_receiver(kaa_client_get_context(kaa_client)->configuration_manager, &receiver);
   sndc_printf("Configuration setting done. %d\n", kaa_error);
   //sndc_thrd_delay(TRACE_DELAY * SNDC_MILLISECOND);
   const kaa_root_configuration_t *root_config = kaa_configuration_manager_get_configuration(kaa_client_get_context(kaa_client)->configuration_manager);
   kaa_on_configuration_updated(NULL, root_config);

   //set SW2 button as key input
   //sndc_io_ctrl(BUTTON,
   //             IO_PIN_FUNC_PULL_UP,
   //             IO_PIN_DRIVE_DEFAULT,
   //             IO_PIN_SLEW_RATE_DEFAULT);
   //sndc_io_setMode(BUTTON, IO_MODE_KEY);

   //sndc_device_config = sndc_config_get();

   /* clean all profiles */
   //sndc_profile_eraseAll();
   //sndc_printf("Press SW2 to start test. \n");

   start_client();

   //infinite thread loop, button press is monitored by system events
   while(1)
   {

      if (ip_connected && !kaa_started) {
          kaa_client_start(kaa_client, NULL, NULL, 0);
          kaa_started = true;
      }
      //thread sleep for 500 ms
      sndc_thrd_delay(500 * SNDC_MILLISECOND);
   }
}
int main(int argc, char *argv[]) {	
	printf(".--FILE TRANSFER CLIENT --.\n");
	if(!processArguments(argc, argv)) return -1;
	start_client(port,ip,remoteFilename,localFilename);
}
Пример #23
0
static bool_t APP_handle_msg(sndc_appmsg_msg_t* msg)
{
   bool_t consumed = FALSE;
   switch(msg->id)
   {
      case SNDC_APPMSG_SCAN_COMPLETED:
      {
         sndc_printf("SNDC_APPMSG_SCAN_COMPLETED\n");
         break;
      }
      case SNDC_APPMSG_SCAN_IND:
      {
         sndc_printf("SNDC_APPMSG_SCAN_IND\n");
         break;
      }
      case SNDC_APPMSG_P2P_EVENT:
      {
         sndc_printf("SNDC_APPMSG_P2P_EVENT\n");
         break;
      }
      case SNDC_APPMSG_CM_EVENT:
      {
        sndc_printf("SNDC_APPMSG_CM_EVENT\n");
        sndc_appmsg_cmEvent_t *cm_event = (sndc_appmsg_cmEvent_t *)msg->par;

        sndc_printf("GOT SNDC_APPMSG_CM_EVENT FROM PROFILE ID: %d WITH ID: %d \n", cm_event->priv.profileID, cm_event->id);
        switch(cm_event->id)
        {
         case EVENT_TYPE_CM_PEER_STATUS:
         {
            switch(cm_event->priv.u.peer_status){
               case SNDC_CM_WLAN_DISCONNECTED: sndc_printf( "SNDC_CM_WLAN_DISCONNECTED\n"); break;
               case SNDC_CM_WLAN_CONNECT_TIMEOUT: sndc_printf( "SNDC_CM_WLAN_CONNECT_TIMEOUT\n"); break;
               case SNDC_CM_WLAN_CONNECT_FAILED: sndc_printf( "SNDC_CM_WLAN_CONNECT_FAILED\n"); break;
               case SNDC_CM_WLAN_WPS_FAILED: sndc_printf( "SNDC_CM_WLAN_WPS_FAILED\n"); break;
               case SNDC_CM_WLAN_WPS_TIMEOUT: sndc_printf( "SNDC_CM_WLAN_WPS_TIMEOUT\n"); break;
               case SNDC_CM_WLAN_CONNECTED: sndc_printf( "SNDC_CM_WLAN_CONNECTED\n"); break;
               default: sndc_printf( "[%d] peer_status:%d  \n",cm_event->priv.profileID, cm_event->priv.u.peer_status); break;
            }
            break;
         }
         case EVENT_TYPE_CM_CLIENT_STATUS:
            break;
         case EVENT_TYPE_CM_GO_STATUS:
            break;
         case EVENT_TYPE_CM_IP_ACQUIRED:
         {
            sndc_profile_ipConfig_t *ipconfig = cm_event->priv.u.ip_acquired.ipconfig;
            sndc_printf("**********************\n");
            sndc_printf("IP acquired, status = %d\n", cm_event->priv.u.ip_acquired.status);
            if(cm_event->priv.u.ip_acquired.status == 0)
            {
               assert(ipconfig);
               sndc_printf("IP addr: %s\n", sndc_inet_ntoa(ipconfig->ip_address));
               sndc_printf("Netmask: %s\n", sndc_inet_ntoa(ipconfig->netmask));
               sndc_printf("Gateway: %s\n", sndc_inet_ntoa(ipconfig->gateway));
               ip_connected = true;
               sndc_sys_initRandom(sndc_sys_getTimestamp_msec());
            }
            sndc_printf("**********************\n");


            break;
         }
         case EVENT_TYPE_CM_AUTO_MODE_STATE_CHANGED:
         {
            sndc_printf( "[%d] AutoMode state changed:%d  \n",cm_event->priv.profileID, cm_event->priv.u.auto_mode_state);
            break;
         }

        }

        break;
      }
      case SNDC_APPMSG_IO_EVENT:
      {
         sndc_printf("SNDC_APPMSG_IO_EVENT\n");
         sndc_appmsg_ioEvent_t *io_event = (sndc_appmsg_ioEvent_t *)msg->par;
         if (testDone) {
             sndc_printf("SNDC_APPMSG_IO_EVENT level %d, pinMask %d\n", io_event->level, io_event->pin_mask);
         } else {
             testDone  = true;
             sndc_printf("Button pressed. \n");
             start_client();
         }
         break;
      }

      default:
         break;
   }

   return consumed;
}
Пример #24
0
int main(int argc, char *argv[])
{
    int bcSock, udpSocket;                        
    struct sockaddr_in broadcastAddr; 
    char *broadcastIP, strbuffer[255], buffer[255];                
    unsigned short broadcastPort;     
    pid_t forkID; //es un int                 
    
    int broadcastPermission;          
    unsigned int sendStringLen; 

	int status;
	int i;
	int found=0,size = 0;
	struct sockaddr_in udpClient,udpServer;
	socklen_t addrlen = sizeof(udpClient);
	char ip[17], *knownHosts[20];
	static char chosenip[17];
	static char filename[255];
	static char localFilename[255];
	//u_short clientPort;

///El siguiente código lo utilizo para obtener la ip de mi propia PC en la interfaz especificada
struct ifaddrs *ifaddr, *ifa;
    int s;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1) 
    {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }

for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) 
    {
        if (ifa->ifa_addr == NULL)
            continue;  

        s=getnameinfo(ifa->ifa_addr,sizeof(struct sockaddr_in),host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
	//Para interfaz cableada eth0 y wireless wlan0, para loopback cambiar a lo
        if((strcmp(ifa->ifa_name,"eth0")==0)&&(ifa->ifa_addr->sa_family==AF_INET))
        {
            if (s != 0)
            {
                printf("getnameinfo() failed: %s\n", gai_strerror(s));
                exit(EXIT_FAILURE);
            }
            printf("\tInterface : <%s>\n",ifa->ifa_name );
            printf("\t  Address : <%s>\n", host); 
        }
    }
	freeifaddrs(ifaddr);

/////////////fin de código para encontrar mi propia dirección IP.

    if (argc < 3)                     
    {
        //fprintf(stderr,"Usage:  %s <IP Address> <Port> <Send String>\n", argv[0]);
	fprintf(stderr,"Usage:  %s <IP Address> <Port>\n", argv[0]);
        exit(1);
    }

    broadcastIP = argv[1];            /* First arg:  broadcast IP address */ 
    broadcastPort = atoi(argv[2]);    /* Second arg:  broadcast port */
    sprintf(strbuffer,"WHO IS THERE %i\r\n\r\n",(int)broadcastPort);	
	//Creamos bcSock, el socket para enviar	broadcast
	bcSock = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
	if(bcSock == -1) {
		fprintf(stderr,"Can't create Socket");
		return 1;
	}
  	
	//Creamos el udpSocket para recibir mensajes
	udpSocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if(udpSocket == -1) {
		fprintf(stderr,"Can't create UDP Socket");
		return 1;
	}

    broadcastPermission = 1;
    status = setsockopt(bcSock, SOL_SOCKET, SO_BROADCAST, (void *) &broadcastPermission, sizeof(broadcastPermission));
    if(status == -1) {
		fprintf(stderr,"Can't set Brodcast Option");
		return 1;
    }

    memset(&broadcastAddr, 0, sizeof(broadcastAddr));   
    broadcastAddr.sin_family = AF_INET;                 
	inet_pton(AF_INET,broadcastIP,&broadcastAddr.sin_addr.s_addr); 
    broadcastAddr.sin_port = htons(broadcastPort);         
	 sendStringLen = strlen(strbuffer);  

    udpServer.sin_family = AF_INET;
    inet_pton(AF_INET,"0.0.0.0",&udpServer.sin_addr.s_addr);
    udpServer.sin_port = htons(5000);
	//con bind asociamos el socket para recibir (udpSocket) a la dirección del udpServer)
    status = bind(udpSocket, (struct sockaddr*)&udpServer,sizeof(udpServer));
	if(status != 0) { 
	  fprintf(stderr,"Can't bind");
    }	
	forkID = fork(); //////////////START FORK
	////Checar donde poner los exit() y donde cerrar los sockets UDP....
	if(forkID == -1) {
			fprintf(stderr,"Cant Fork\n");
		} else if(forkID == 0) {
			//Soy el HIJO
			//printf("Recibimos: OK\n");
		while(1) {
		bzero(buffer,255);
		status = recvfrom(udpSocket, buffer, 255, 0, (struct sockaddr*)&udpClient, &addrlen );
		////ver por donde se recibe los mensajes del sender para en el sender recibir el ME PC2
		inet_ntop(AF_INET,&(udpClient.sin_addr),ip,INET_ADDRSTRLEN);
	//	clientPort = ntohs(udpClient.sin_port);
		////no se esta recibiendo el buffer que manda el listen en ME PC2....checar
		
		if(strcmp(ip,host)!=0){ //nos aseguramos de no imprimir las respuestas de mi propia IP.
		//fprintf(stderr,"Recibimos: %s desde: [%s:%i]\n",buffer,ip,clientPort);
		
		///Creamos la lista de hosts conocidos con un arreglo de apuntadores a char knownHosts
		for(i=0; i < size; i++) {
   			if(strcmp(knownHosts[i],ip)==0) {
      			  found = 1;
			break;
   			}
		} 

			if(!found) {
			   knownHosts[size] = (char *) malloc(16);
 			   strcpy(knownHosts[size],ip);
   			   size++;
			} 
				
		}	
		
		i=0;
		///En cada respuesta imprimimos la lista de hosts conocidos
		fprintf(stderr,"Hosts conocidos por ");
		while(knownHosts[i]!=NULL){
		
		fprintf(stderr,"%s \n",knownHosts[i]);
		i++;	
		}


		udpClient.sin_port = 5000;
		bzero(buffer,255);
   	    fflush(stdout);
	}
	
	close(udpSocket);
			//exit(0);
			return 0;
		} 
	else {
		//	//SOY EL PADRE
		for(i=0; i<2; i++) {  //Este hilo (proceso) sólo manda WHO IS THERE cada 3 segundos
		status = sendto(bcSock,strbuffer,sendStringLen,0,(struct sockaddr*)&broadcastAddr, sizeof(broadcastAddr));    
      ///Respuestas cada 3 segundos
        sleep(1);   
    	}
		//exit(0);///
		//close(udpSocket); 

	} /////////////////////FIN FORK
		//exit(0);
//close(udpSocket);
fprintf(stderr,"\nElija una IP\n");
gets(chosenip);
fprintf(stderr,"\nUsted escogió al host: %s\n",chosenip );
get_LIST(5000,chosenip); 
fprintf(stderr,"\nAhora teclea el archivo que deseas obtener\n");
gets(filename);
fprintf(stderr,"\nTeclea con qué nombre quieres guardar el archivo\n");
gets(localFilename);
start_client(5000,chosenip,filename,localFilename);
sleep(15); 


return 0;
} //fin main
Пример #25
0
void doClient(void)
{
    int forward_id;
    ps_recv_info_t rinfo;
    ps_send_info_t sinfo;
    FILE *output = NULL;
    PSP_PortH_t porth;
    char *buf, *buf2;

    buf = malloc(arg_maxmsize);
    if (!buf) { perror("malloc(buf)"); exit(1); }
    buf2 = malloc(arg_maxmsize);
    if (!buf2) { perror("malloc(buf2)"); exit(1); }

    output = stdout;

    if (arg_ofile) {
	output = fopen(arg_ofile, "w");
	if (!output) {
	    fprintf(stderr, "Cant open file '%s' for writing : %s\n",
		    arg_ofile, strerror(errno));
	    exit(1);
	}
    } else if (arg_ocmd) {
	output = popen(arg_ocmd, "w");
	if (!output) {
	    fprintf(stderr, "Cant start output command '%s' : %s\n",
		    arg_icmd, strerror(errno));
	    exit(1);
	}
    }

    porth = start_client(&forward_id);
    ps_recv_info_init(&rinfo, porth);
    ps_send_info_init(&sinfo, porth, forward_id);
    PSP_StopListen(porth);

    stat_time_start = getusec();
    while (1) {
	int len;
	char *tmp;

	len = ps_recv(&rinfo, buf, arg_maxmsize);
	ps_send(&sinfo, buf, len);

	if (len <= 0) break;
	assert(fwrite(buf, 1, len, output) == (unsigned) len);

	tmp = buf; buf = buf2; buf2 = tmp;

	if (timer_called) {
	    if (arg_manual) print_stat(0);
	    timer_called = 0;
	}
    }

    if (arg_ofile) {
	fclose(output);
    } else if (arg_ocmd) {
	pclose(output);
    }
    ps_recv_close(&rinfo);
    ps_send_close(&sinfo);
    free(buf2);
    free(buf);
}
Пример #26
0
bool rvl_connection_new(char *host)
{
	return (host == NULL) ? start_server() : start_client(host);
}
Пример #27
0
int main(int argc, char **argv)
{
  qi::Application app(argc, argv);

  std::string usage = "If no mode is specified, run client and server in same process\n";

  po::options_description desc(std::string("Usage:\n ")+argv[0]+"\n" + usage);
  desc.add_options()
    ("help,h", "Print this help.")
    ("all", po::value<std::string>()->default_value("tcp://0.0.0.0:0"), "(default) Run all in the same process.")
    ("client,c", po::value<std::string>(), "Run as a client (tcp://xxx.xxx.xxx.xxx:xxxxx).")
    ("server,s", po::value<std::string>()->implicit_value("tcp://0.0.0.0:0"), "Run as a server.")
    ("gateway", po::value<std::string>(), "Run as a gateway.")
    ("local", "Run in local.")
    ("thread", po::value<int>()->default_value(1, "1"),
     "Number of thread to launch for clients")
    ("valgrind", "Set low loopcount and wait for valgrind.")
    ("gateway", "Run without gateway.")
    ("rstart", po::value<int>()->default_value(0, "0"), "rstart")
    ("rend", po::value<int>()->default_value(20, "20"), "rend")
    ("pipeline", po::value<int>()->default_value(1, "1"), "Max number of parallel calls to run")
    ("threadsafe", po::bool_switch()->default_value(false), "Declare threadsafe service")
    ("msdelay", po::value<int>()->default_value(0, "0"), "Delay in milliseconds to simulate long call")
    ;

  desc.add(qi::details::getPerfOptions());

  po::variables_map vm;
  po::store(po::command_line_parser(argc, argv)
            .options(desc).run(), vm);
  po::notify(vm);

  if (vm.count("help")) {
    std::cout << desc << std::endl;
    return EXIT_SUCCESS;
  }

  if (vm.count("gateway"))
    noGateway = false;

  if (vm.count("valgrind")) {
    gLoopCount = 500;
    valgrind = true;
  }


  if (vm.count("client") + vm.count("server") + !vm["all"].defaulted() + vm.count("gateway") + vm.count("local") > 1) {
    std::cerr << desc << std::endl << "You must put at most one option between [all|client|server|gateway|local]" << std::endl;
    return EXIT_FAILURE;
  }

  if (!vm["thread"].defaulted() && (vm.count("server") != 0 || vm.count("gateway") != 0)) {
    std::cerr << "[thread] is useless with [server] or [gateway]" << std::endl;
  }

  rstart = vm["rstart"].as<int>();
  rend   = vm["rend"].as<int>();
  pipeline = vm["pipeline"].as<int>();
  threadsafe = vm["threadsafe"].as<bool>();
  msDelay = vm["msdelay"].as<int>();

  out = new qi::DataPerfSuite("qimessaging", "transport", qi::DataPerfSuite::OutputData_Period, vm["output"].as<std::string>());

  if (vm.count("client"))
  {
    serverUrl = qi::Url(vm["client"].as<std::string>());
    int threadc = vm["thread"].as<int>();
    start_client(threadc);
  } else if (vm.count("server")) {
    serverUrl = vm["server"].as<std::string>();
    return main_server();
  } else if (vm.count("gateway")) {
    serverUrl = vm["gateway"].as<std::string>();
    return main_gateway(serverUrl);
  } else if (vm.count("local")) {
    return main_local();
  } else {
    //start the server
    int threadc = vm["thread"].as<int>();
    serverUrl = vm["all"].as<std::string>();
    allInOne = true;
    boost::thread threadServer1(boost::bind(&main_server));
    do {
      qi::os::msleep(500); // give it time to listen
    } while (!serverReady); // be nice for valgrind
    if (!noGateway)
      boost::thread threadServer2(boost::bind(&main_gateway, serverUrl));
    qi::os::sleep(1);

    start_client(threadc);
  }

  delete out;

  return EXIT_SUCCESS;
}
Пример #28
0
int
start_broker(int num_client, int num_server)
{
    int available_workers = 0;
    char* work_queue[10];
    void* ctx = zmq_ctx_new();
    void* front = zmq_socket(ctx, ZMQ_ROUTER);
    void* back = zmq_socket(ctx, ZMQ_ROUTER);

    zmq_bind(front, "ipc://front.ipc");
    zmq_bind(back, "ipc://back.ipc");

    start_client(num_client);
    start_server(num_server);

    while (1) {
        zmq_pollitem_t items[] = {
            { back, 0, ZMQ_POLLIN, 0 },
            { front, 0, ZMQ_POLLIN, 0 },
        };
        int ret = zmq_poll(items, available_workers ? 2 : 1, -1);
        if (-1 == ret)
            break;

        if (items[0].revents & ZMQ_POLLIN) {
            char client_id[16] = {0};
            char buf[128] = {0};
            char* server_id = (char*)calloc(16, 0);
            zmq_recv(back, server_id, 16, 0);
            work_queue[available_workers++] = server_id;

            zmq_recv(back, buf, sizeof(buf), 0);
            zmq_recv(back, client_id, sizeof(client_id), 0);

            if (0 != strcmp("READY", client_id)) {
                zmq_recv(back, buf, sizeof(buf), 0);

                memset(buf, 0, sizeof(buf));
                zmq_recv(back, buf, sizeof(buf), 0);
                zmq_send(front, client_id, strlen(client_id), ZMQ_SNDMORE);
                zmq_send(front, "", 0, ZMQ_SNDMORE);
                zmq_send(front, buf, strlen(buf), 0);
                if (0 == --num_client)
                    break;
            }
        }

        if (items[1].revents & ZMQ_POLLIN) {
            char client_id[16] = {0};
            char buf[128];
            zmq_recv(front, client_id, sizeof(client_id), 0);
            zmq_recv(front, buf, sizeof(buf), 0);
            memset(buf, 0, sizeof(buf));
            zmq_recv(front, buf, sizeof(buf), 0);

            zmq_send(back, work_queue[0], strlen(work_queue[0]), ZMQ_SNDMORE);
            zmq_send(back, "", 0, ZMQ_SNDMORE);
            zmq_send(back, client_id, strlen(client_id), ZMQ_SNDMORE);
            zmq_send(back, "", 0, ZMQ_SNDMORE);
            zmq_send(back, buf, strlen(buf), 0);

            free(work_queue[0]);
            DEQUE(work_queue);
            --available_workers;
        }
    }

    zmq_close(back);
    zmq_close(front);
    zmq_ctx_destroy(ctx);

    return 0;
}
Пример #29
0
JNIEXPORT jint JNICALL Java_cn_edu_hust_buildingtalkback_jni_NativeInterface_startClient(
		JNIEnv *env, jclass clazz)
{
	LOG_FUNC();
	return start_client();
}
Пример #30
0
int main(int argc, char *argv[]){
    /* initialize options */
    init_options();

    /* parse command line args */
    int c;
    while((c = getopt(argc, argv, ":hve:p:lku")) != -1){
        switch(c){
            case 'h': help(argv);
                      exit(EXIT_SUCCESS);

            case 'v': o.verbose = 1;
                      break;

            case 'e': o.execcommand = 1;
                      o.command = optarg;
                      break;

            case 'p': o.port = validate_port(optarg);
                      break;

            case 'l': o.listen = 1;
                      break;

            case 'k': o.keepopen = 1;
                      break;

            case 'u': o.udp = 1;
                      break;

            case ':': bye("-%c requires argument\n", optopt);

            /* case ? */
            default: bye("unknown option -%c\n", optopt);

        }/* switch */
    }/* while */

    /* do some checking */

    /* -k specified without -l */
    if(o.keepopen && !o.listen){
        bye("cannot specify -k without -l\n");
    }

    /* -p not specified with -l */
    if(o.listen && !o.port){
        bye("must specify -p with -l\n");
    }


    /* get IP-address and port in case of client mode */
    if(!o.listen && optind < argc){
        o.target = argv[optind++];

        if(optind > argc){
            bye("No port specified\n");
        }

        o.port = validate_port(argv[optind]);

    } else if(!o.listen){
        help(argv);
        exit(EXIT_FAILURE);
    }

    if(o.listen)
        start_server();
    else
        start_client();

    return 0;
}/* main() */