示例#1
0
int main(int argc, char *argv[])
{
	int i;
	int sockfd;
	struct sockaddr_in servaddr;

	if (argc != 2) {
		puts("usage: client address");
		return 0;
	}

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
	servaddr.sin_port = htons(SERV_PORT);

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0) {
		perror("socket create error");
		return 1;
	}

	if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
		perror("connect socket error");
		return 1;
	}

	client_process(stdin, sockfd);
	return 0;
}
示例#2
0
文件: client.c 项目: hermixy/qtun
void client_loop(int remotefd, int localfd)
{
    fd_set set;
    int max;
    this.client.status = CLIENT_STATUS_NORMAL | CLIENT_STATUS_WAITING_HEADER;
    this.client.want = sizeof(msg_t);
    this.client.buffer = this.client.read = pool_room_alloc(&this.pool, RECV_ROOM_IDX, this.client.want);
    int keepalive_send = 0;
    int rc;
    if (this.client.buffer == NULL)
    {
        fprintf(stderr, "Not enough memory\n");
        return;
    }
    this.keepalive_replyed = 1;
    while (1)
    {
        struct timeval tv = {1, 0};
        FD_ZERO(&set);
        FD_SET(remotefd, &set);
        FD_SET(localfd, &set);
        max = remotefd > localfd ? remotefd : localfd;

        if (this.keepalive_replyed && (time(NULL) - this.keepalive) > KEEPALIVE_INTERVAL)
        {
            msg_t* msg = new_keepalive_msg(1);
            write_n(remotefd, msg, sizeof(msg_t));
            printf("send keepalive message\n");
            this.keepalive = time(NULL);
            this.keepalive_replyed = 0;
            pool_room_free(&this.pool, MSG_ROOM_IDX);
            keepalive_send = 1;
        }

        max = select(max + 1, &set, NULL, NULL, &tv);
        if (max > 0)
        {
            rc = client_process(max, &set, remotefd, localfd);
            switch (rc)
            {
            case RETURN_CONNECTION_CLOSED:
            case RETURN_READ_ERROR:
                pool_room_free(&this.pool, RECV_ROOM_IDX);
                return;
            }
        }

        if (keepalive_send && !this.keepalive_replyed && (time(NULL) - this.keepalive) > KEEPALIVE_TIMEOUT)
        {
            fprintf(stderr, "keepalive reply timeouted, connection closed\n");
            pool_room_free(&this.pool, RECV_ROOM_IDX);
            return;
        }
    }
}
void event_raised_callback(evutil_socket_t socket, short event, void *context)
{
  client_st *client = (client_st *)context;
  
  /* The following will trigger processing within burrow: */
  burrow_event_raised(client->burrow, (int)socket, event);

  /* Which we will then attempt to take advantage of;
     if burrow is still waiting, this call will simply do no work */
  client_process(client);
}
void 		client_handle(networking::Client *c)
{
	pid_t	pid = fork();
	if (pid == -1)
	{
		std::cerr << "Impossible de forker pour le client @" << c->get_ip_address() << std::endl;
	}
	else if (pid == 0)
	{
		c->set_pid(pid);
		client_process(c);
	}
}
示例#5
0
void 
pthread_handle (void)
{
    int fd;
    for (;;) {
        struct request *get = get_request();
        if (get != NULL) {
            fd = (get->fd);
            client_process(fd);
        }
    }
    
}
示例#6
0
/* 
 * This is the function for handling a _single_ request.  Understand
 * what each of the steps in this function do, so that you can handle
 * _multiple_ requests.  Use this function as an _example_ of the
 * basic functionality.  As you increase the server in functionality,
 * you will want to probably keep all of the functions called in this
 * function, but define different code to use them.
 */
void
server_single_request(int accept_fd)
{
	int fd;

	/* 
	 * The server thread will always want to be doing the accept.
	 * That main thread will want to hand off the new fd to the
	 * new threads/processes/thread pool.
	 */
	fd = server_accept(accept_fd);
	client_process(fd);

	return;
}
示例#7
0
文件: network.c 项目: hermixy/qtun
void client_loop(int remotefd, int localfd)
{
    fd_set set;
    int max;
    while (1)
    {
        struct timeval tv = {60, 0};
        FD_ZERO(&set);
        FD_SET(remotefd, &set);
        FD_SET(localfd, &set);
        max = remotefd > localfd ? remotefd : localfd;

        max = select(max + 1, &set, NULL, NULL, &tv);
        if (max > 0) client_process(max, &set, remotefd, localfd);
    }
}
示例#8
0
   //  Get and process messages forever or until interrupted
   void
   start_brokering() {
      while (!s_interrupted) {
          zmq::pollitem_t items [] = {
              { *m_socket,  0, ZMQ_POLLIN, 0 } };
          zmq::poll (items, 1, HEARTBEAT_INTERVAL);

          //  Process next input message, if any
          if (items [0].revents & ZMQ_POLLIN) {
              zmsg *msg = new zmsg(*m_socket);
              if (m_verbose) {
                  s_console ("I: received message:");
                  msg->dump ();
              }
              std::string sender = std::string((char*)msg->pop_front ().c_str());
              msg->pop_front (); //empty message
              std::string header = std::string((char*)msg->pop_front ().c_str());

//              std::cout << "sbrok, sender: "<< sender << std::endl;
//              std::cout << "sbrok, header: "<< header << std::endl;
//              std::cout << "msg size: " << msg->parts() << std::endl;
//              msg->dump();
              if (header.compare(MDPC_CLIENT) == 0) {
                  client_process (sender, msg);
              }
              else if (header.compare(MDPW_WORKER) == 0) {
                  worker_process (sender, msg);
              }
              else {
                  s_console ("E: invalid message:");
                  msg->dump ();
                  delete msg;
              }
          }
          //  Disconnect and delete any expired workers
          //  Send heartbeats to idle workers if needed
          if (s_clock () > m_heartbeat_at) {
              purge_workers ();
              for (std::vector<worker*>::iterator it = m_waiting.begin();
                    it != m_waiting.end() && (*it)!=0; it++) {
                  worker_send (*it, (char*)MDPW_HEARTBEAT, "", NULL);
              }
              m_heartbeat_at = s_clock () + HEARTBEAT_INTERVAL;
          }
      }
   }
示例#9
0
文件: client.c 项目: frecel/gtetrinet
void client_init (const char *s, const char *n)
{
    int i;
    GTET_O_STRCPY(server, s);
    GTET_O_STRCPY(nick, n);

    connectingdialog_new ();

    /* wipe spaces off the nick */
    for (i = 0; nick[i]; i ++)
      if (isspace (nick[i]))
        nick[i] = 0;

    /* set the game mode */
    inmsg_change();
    
    client_process ();
}
示例#10
0
int DiscussClient::Connect()
{
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(servSettings.ss_port);
	servaddr.sin_addr.s_addr = inet_addr(servSettings.ss_addr.c_str());

	sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

	socklen_t socklen = sizeof(servaddr);
	if(connect(sockfd, (struct sockaddr*)&servaddr, socklen) == -1)
	{
		perror("connect");
		return -1;
	}

	client_process();
}
示例#11
0
void
server_processes(int accept_fd)
{
    pid_t childID; 
    int fd, status, endID, i;
    int count = 0;
    int temp = 0;
    pid_t *connect = malloc(sizeof(pid_t)*MAX_CONCURRENCY);
    for(;;){
        while (count >= MAX_CONCURRENCY) {
            wait(&status);
            int tempCount = count;
            count = 0;
            for (i = 0 ; i < tempCount ; i++) {
                if (waitpid(connect[i], &status, WNOHANG|WUNTRACED)) {
                    connect[temp] = connect[i];
                    temp++;
                } else 
                    count++;
            }
        }
        if (count >= MAX_CONCURRENCY) 
            continue;
        else {
            fd = server_accept(accept_fd);
            if (childID == -1) {
                perror("FORK ERROR");
                break;
            }
            else if (childID == 0) {
                client_process(fd);
                break;
            }
            else {
                childID = fork();
                temp++;
                connect[temp] = childID;
                count++;
            }
        }
    }
	return;
}
示例#12
0
文件: main.c 项目: kalmuthu/threads
/* 
 * This is the function for handling a _single_ request.  Understand
 * what each of the steps in this function do, so that you can handle
 * _multiple_ requests.  Use this function as an _example_ of the
 * basic functionality.  As you increase the server in functionality,
 * you will want to probably keep all of the functions called in this
 * function, but define different code to use them.
 */
void
server_single_request(int accept_fd)
{
	int fd;

	/* 
	 * The server thread will always want to be doing the accept.
	 * That main thread will want to hand off the new fd to the
	 * new threads/processes/thread pool.
	 */
	fd = server_accept(accept_fd);
	client_process(fd);

	/* 
	 * A loop around these two lines will result in multiple
	 * documents being served.
	 */

	return;
}
示例#13
0
文件: main.c 项目: hsjhsj110cs/hehe
void*
worker_thread_routine(void)
{
    int fd;
    job *job_to_do;

    while(1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        job_to_do = job_get();
        fd = job_to_do->fd;
        free(job_to_do);
        client_process(fd);
        pthread_mutex_unlock(&mutex);

        printf("thd finished\n");
    }
    return NULL;
}
示例#14
0
int main(void)
{
  const int CLIENT_COUNT = 4;
  event_base_st *ev_base;
  burrow_st *burrow;
  client_st *clients[CLIENT_COUNT];
  int i;
  
  burrow = burrow_create("http");
  burrow_set_options(burrow, BURROW_OPT_NONBLOCK);
  /* eday seemed to support this type of interface for backend parameters
     for modularity, stating that most  */
  burrow_set_backend_option_string("server", "burrow.example.com");
  burrow_set_backend_option_int("port", 1234);
  /* We won't implement connection pooling. This is just an example: */
  burrow_set_backend_option_int("connection_pool", 4);
  
  burrow_set_event_fn(burrow, &wait_for_event_callback);
  
  burrow_set_message_fn(burrow, &message_callback);
  burrow_set_queue_fn(burrow, &queue_callback);
  burrow_set_account_fn(burrow, &account_callback);
  burrow_set_error_fn(burrow, &error_callback);

  ev_base = event_base_new(); /* Set up libevent base */
  
  for (i = 0; i < CLIENT_COUNT; i++) {
    client = client_create(burrow, ev_base);
    /* Kick off client processing */
    client_process(client);
  }
  
  event_base_dispatch(ev_base); /* This encapsulates the whole select/wait loop */

  for (i = 0; i < CLIENT_COUNT; i++)
    free(client);

  event_base_free(ev_base);
  burrow_free(burrow);
}
void main()
{
	pid_t pid;
	struct sockaddr_in addr_me;
	if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
	{
		perror("socket");
	}	
	addr_me.sin_family = AF_INET;
	addr_me.sin_port = htons(PORT);
	inet_aton(IPADDR,&addr_me.sin_addr);
	if (bind(sock, (struct sockaddr *)&addr_me, sizeof(addr_me)) == -1)
	{
		perror("bind");
	}
	pid = fork();
	if (pid == 0)
	{
		client_process();
	}
	wait(0);
	close(sock);
}
void client_process()
{
	pid_t pid;
	pthread_t thread;
	char buf[MSGLEN];
	struct sockaddr_in addr_me ,addr_other;
	int struct_len = sizeof(addr_other),i,sock_new;
	if ((sock_new = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
	{
		perror("socket");
	}
	addr_me.sin_family = AF_INET;
	addr_me.sin_port = 0;
	inet_aton(IPADDR,&addr_me.sin_addr);
	if (bind(sock_new, (struct sockaddr *)&addr_me, sizeof(addr_me)) == -1)
	{
		perror("bind");
	}
	pthread_create(&thread,NULL,MulPlex,&sock_new);
	printf("%d\n",htons(addr_other.sin_port));
	for (i=0;i<CLIENT;i++)
	{
		printf("Waiting data\n");
		if (recvfrom(sock,buf,MSGLEN,0,(struct sockaddr *)&addr_other,&struct_len) == -1)
		{
			perror("recvfrom");
		}
		if (sendto(sock_new,"Connection",MSGLEN,0,(struct sockaddr *)&addr_other,struct_len) == -1)
		{
			perror("sendto");
		}
		printf("%s\n", buf);
	}
	pid = fork();
	if (pid == 0)
		client_process();
}
示例#17
0
文件: main.c 项目: JayceYang/usbmuxd
static int main_loop(int listenfd)
{
	int to, cnt, i, dto;
	struct fdlist pollfds;
	struct timespec tspec;

	sigset_t empty_sigset;
	sigemptyset(&empty_sigset); // unmask all signals

	fdlist_create(&pollfds);
	while(!should_exit) {
		usbmuxd_log(LL_FLOOD, "main_loop iteration");
		to = usb_get_timeout();
		usbmuxd_log(LL_FLOOD, "USB timeout is %d ms", to);
		dto = device_get_timeout();
		usbmuxd_log(LL_FLOOD, "Device timeout is %d ms", dto);
		if(dto < to)
			to = dto;

		fdlist_reset(&pollfds);
		fdlist_add(&pollfds, FD_LISTEN, listenfd, POLLIN);
		usb_get_fds(&pollfds);
		client_get_fds(&pollfds);
		usbmuxd_log(LL_FLOOD, "fd count is %d", pollfds.count);

		tspec.tv_sec = to / 1000;
		tspec.tv_nsec = (to % 1000) * 1000000;
		cnt = ppoll(pollfds.fds, pollfds.count, &tspec, &empty_sigset);
		usbmuxd_log(LL_FLOOD, "poll() returned %d", cnt);
		if(cnt == -1) {
			if(errno == EINTR) {
				if(should_exit) {
					usbmuxd_log(LL_INFO, "Event processing interrupted");
					break;
				}
				if(should_discover) {
					should_discover = 0;
					usbmuxd_log(LL_INFO, "Device discovery triggered");
					usb_discover();
				}
			}
		} else if(cnt == 0) {
			if(usb_process() < 0) {
				usbmuxd_log(LL_FATAL, "usb_process() failed");
				fdlist_free(&pollfds);
				return -1;
			}
			device_check_timeouts();
		} else {
			int done_usb = 0;
			for(i=0; i<pollfds.count; i++) {
				if(pollfds.fds[i].revents) {
					if(!done_usb && pollfds.owners[i] == FD_USB) {
						if(usb_process() < 0) {
							usbmuxd_log(LL_FATAL, "usb_process() failed");
							fdlist_free(&pollfds);
							return -1;
						}
						done_usb = 1;
					}
					if(pollfds.owners[i] == FD_LISTEN) {
						if(client_accept(listenfd) < 0) {
							usbmuxd_log(LL_FATAL, "client_accept() failed");
							fdlist_free(&pollfds);
							return -1;
						}
					}
					if(pollfds.owners[i] == FD_CLIENT) {
						client_process(pollfds.fds[i].fd, pollfds.fds[i].revents);
					}
				}
			}
		}
	}
	fdlist_free(&pollfds);
	return 0;
}
示例#18
0
文件: main.c 项目: TanND/Electronic
//*****************************************************************************************
//
// Function : main
// Description : main program, 
//
//*****************************************************************************************
int main (void)
{
	// change your mac address here
	avr_mac.byte[0] = 'A';
	avr_mac.byte[1] = 'V';
	avr_mac.byte[2] = 'R';
	avr_mac.byte[3] = 'P';
	avr_mac.byte[4] = 'O';
	avr_mac.byte[5] = 'R';

	// read avr and server ip from eeprom
	eeprom_read_block ( &avr_ip, ee_avr_ip, 4 );
	eeprom_read_block ( &server_ip, ee_server_ip, 4 );
	
	// setup port as input and enable pull-up
	SW_DDR &= ~ ( _BV( SW_MENU ) | _BV( SW_EXIT ) | _BV( SW_UP ) | _BV( SW_DW ) );
	SW_PORT |= _BV( SW_MENU ) | _BV( SW_EXIT ) | _BV( SW_UP ) | _BV( SW_DW );
	SFIOR &= ~_BV( PUD );

	// setup lcd backlight as output
	LCD_BL_DDR |= _BV( LCD_BL_PIN );
	// lcd backlight on
	LCD_BL_PORT |= _BV( LCD_BL_PIN );
	
	// setup clock for timer1
	TCCR1B = 0x01;	// clk/1 no prescaling

	// initial adc, lcd, and menu
	adc_init();
	lcd_init ();
	menu_init ();

	// set LED1, LED2 as output */
	LED_DDR |= _BV( LED_PIN1_DDR ) | _BV( LED_PIN2_DDR );
	// set LED pin to "1" ( LED1,LED2 off)
	LED_PORT |= _BV( LED_PIN1 ) | _BV( LED_PIN2 );

	// initial enc28j60
	enc28j60_init( (BYTE*)&avr_mac );
	
	// loop forever
	for(;;)
	{
		// wait until timer1 overflow
		while ( (TIFR & _BV ( TOV1 )) == 0 );
		TIFR |= _BV(TOV1);
		TCNT1 = 1536;	// Timer1 overflow every 1/16MHz * ( 65536 - 1536 ) = 4ms, 250Hz

		// general time base, generate by timer1
		// overflow every 1/250 seconds
		time_base ();
		
		// read temparature
		adc_read_temp();

		// server process response for arp, icmp, http
		server_process ();

		// send temparature to web server unsing http protocol
		// disable by default.
		client_process ();

		// lcd user interface menu
		// setup IP address, countdown timer
		menu_process ();

		// display AVR ethernet status
		// temparature, AVR ip, server ip, countdown time
		standby_display ();
	}

	return 0;
}
示例#19
0
文件: main.c 项目: nwcfang/rs232test
int main(int argc, const char* argv[])
{
    pid_t server_child = 0;
    int fd;
    int res = 0, status;
    struct sigaction sigchildAction;

    tio_param sParam [] = {
       {"D:", "DURATION", "Duration"},
       { "m:", "PORTSPEED", "Prot speed"},
       { "s:", "SENDPACKSLENGTH", "Send pack length"},
       { "d", "SERVERMODE", "Server mode" },
       { "l", "CLIENTMODE", "Client mode" },
       { "L", "CLIENTSERVERMODE", "Client/Server mode" }, 
       {NULL, NULL, NULL}
    };

    sigchildAction.sa_handler = termination_signal;
    sigchildAction.sa_flags    = SA_NOCLDSTOP;
    sigemptyset(&(sigchildAction.sa_mask));
    sigaddset(&(sigchildAction.sa_mask),SIGTERM);

    if (sigaction(SIGTERM, &sigchildAction, NULL))
    {
        perror("Signal SIGTERM registration failed");
        return -1;
    }
    if (sigaction(SIGINT, &sigchildAction, NULL))
    {
        perror("Signal SIGINT registration failed");
        return -1;
    }

    // Инициализация tio и разбор входных параметров командной строки  
    tioInit( "alpha", "RS232 test", sParam, argc, argv); 
    
    if (write_configuration(&config))
    {
        fputs("Congiguration read error\n", stderr);
        return -1;
    }
    
    fd = open_serial_port( tio_argv[0], tioGetDefL( "PORTSPEED", 115200 ));
    if (fd < 0)
    {
        return -1;
    }
    config.outputDevice = fd;
    
    if ( tioGetL( "CLIENTSERVERMODE" ) > 0 )
    {
        server_child = fork();
    }
    if ((server_child == 0) && (tioGetL( "CLIENTSERVERMODE" ) || tioGetL( "SERVERMODE" ) ) )
    {
        if (server_process(&config))
        {
            return -1;
        }
    }
    else if ( tioGetL( "CLIENTSERVERMODE" ) || tioGetL( "CLIENTMODE" ))
        res = client_process(&config);
    else 
    {
        DEBUGMSG("Undefined target action");
        return -1;
    }

    if (server_child != 0)
        waitpid(server_child, &status, WNOHANG);

    // Завершение работы библиотеки tio  
    tioFinish(0);

    return (int)(res || status);
    /*return 0;*/
}
示例#20
0
void
server_multiple_requests(int accept_fd)
{
    for (;;) client_process(server_accept(accept_fd));
	return;
}
示例#21
0
文件: dspamc.c 项目: mark711/mahogany
int
main (int argc, char *argv[])
{
  AGENT_CTX ATX;
  int exitcode = EXIT_SUCCESS;
  buffer *message = NULL;       /* input Message */
  int agent_init = 0;		/* agent is initialized */

  setbuf (stdout, NULL);	/* unbuffered output */
#ifdef DEBUG
  DO_DEBUG = 0;
#endif

  srand ((long) time << (long) getpid());
  umask (006);

#ifndef DAEMON
  LOG(LOG_ERR, ERR_DAEMON_NO_SUPPORT);
  exit(EXIT_FAILURE);
#endif

  /* Read dspam.conf into global config structure (ds_config_t) */

  agent_config = read_config(NULL);
  if (!agent_config) {
    LOG(LOG_ERR, ERR_AGENT_READ_CONFIG);
    exitcode = EXIT_FAILURE;
    goto BAIL;
  }

  if (!_ds_read_attribute(agent_config, "Home")) {
    LOG(LOG_ERR, ERR_AGENT_DSPAM_HOME);
    exitcode = EXIT_FAILURE;
    goto BAIL;
  }

  /* Set up agent context to define behavior of processor */

  if (initialize_atx(&ATX)) {
    LOG(LOG_ERR, ERR_AGENT_INIT_ATX);
    exitcode = EXIT_FAILURE;
    goto BAIL;
  } else {
    agent_init = 1;
  }

  if (process_arguments(&ATX, argc, argv)) {
    LOG(LOG_ERR, ERR_AGENT_INIT_ATX);
    exitcode = EXIT_FAILURE;
    goto BAIL;
  }

  if (apply_defaults(&ATX)) {
    LOG(LOG_ERR, ERR_AGENT_INIT_ATX);
    exitcode = EXIT_FAILURE;
    goto BAIL;
  }

  if (check_configuration(&ATX)) {
    LOG(LOG_ERR, ERR_AGENT_MISCONFIGURED);
    exitcode = EXIT_FAILURE;
    goto BAIL;
  }

  /* Read the message in and apply ParseTo services */

  message = read_stdin(&ATX);
  if (message == NULL) {
    exitcode = EXIT_FAILURE;
    goto BAIL;
  }

  if (ATX.users->items == 0)
  {
    LOG (LOG_ERR, ERR_AGENT_USER_UNDEFINED);
    fprintf (stderr, "%s\n", SYNTAX);
    exitcode = EXIT_FAILURE;
    goto BAIL;
  }

  /* Perform client-based processing */

#ifdef DAEMON
  if (_ds_read_attribute(agent_config, "ClientIdent") &&
      (_ds_read_attribute(agent_config, "ClientHost") ||
       _ds_read_attribute(agent_config, "ServerDomainSocketPath")))
  {
    exitcode = client_process(&ATX, message);
  } else {
    LOG(LOG_ERR, ERR_CLIENT_INVALID_CONFIG);
    exitcode = EINVAL;
  }
#endif

BAIL:

  if (message)
    buffer_destroy(message);

  if (agent_init)
    nt_destroy(ATX.users);

  if (agent_config)
    _ds_destroy_config(agent_config);

  exit (exitcode);
}