예제 #1
0
int main()
{
    DataServer* server = new TCPDataServer();
    server->setup(12345);
    start_listening(server);

    unsigned char* receivedDataBuffer = (unsigned char *)malloc(TCP_MAX_MSG_SIZE);
    int i=0;

    while(true) {
        i++;
        if(server->isConnected()) {

            int receivedSize = server->receiveRawBytes((char *)receivedDataBuffer, TCP_MAX_MSG_SIZE);
            if (receivedSize == 0) {
                std::cout << "disconected" << std::endl;
                start_listening(server);
            }else if(receivedSize > 0) {
                std::cout << receivedDataBuffer << std::endl;
                std::stringstream ss;
                ss << "echo: " << receivedDataBuffer << std::endl;
                server->send(ss.str());
            }
            server->send("test\n");
        }
    }
    std::cout << "end" << std::endl;
}
예제 #2
0
파일: daemon.c 프로젝트: jeffpc/blahgd
int main(int argc, char **argv)
{
	int ret;

	ASSERT0(putenv("TZ=UTC"));

	cmn_err(CE_INFO, "blahgd version %s", version_string);

	/* drop unneeded privs */
	ret = drop_privs();
	if (ret)
		goto err;

	jeffpc_init(&init_ops);
	init_math(true);
	init_pipe_subsys();
	init_req_subsys();
	init_post_subsys();
	init_file_cache();

	ret = config_load((argc >= 2) ? argv[1] : NULL);
	if (ret)
		goto err;

	ret = load_all_posts();
	if (ret)
		goto err;

	handle_signals();

	ret = start_helpers();
	if (ret)
		goto err_helpers;

	ret = start_listening();
	if (ret)
		goto err_helpers;

	accept_conns();

	stop_listening();

	stop_helpers();

	free_all_posts();
	uncache_all_files();

	return 0;

err_helpers:
	stop_helpers();

err:
	DBG("Failed to inintialize: %s", xstrerror(ret));

	return ret;
}
예제 #3
0
 void listen()
 {
     std::lock_guard<std::mutex> lock{listening_mutex_};
     if (!listening_) {
         start_listening();
     }
     if (!listening_) {
         throw std::runtime_error{"Failed to listening"};
     }
 }
예제 #4
0
static void init(void)
{
   init_winsock();
   create_io_completion_port();
   create_listening_socket();
   bind_listening_socket();
   start_listening();
   load_accept_ex();
   start_accepting();
}
예제 #5
0
void TcpServer::accept_handler(const boost::system::error_code & error_code, boost::shared_ptr<tcp::socket> connection, string host, int port)
{
	// Log error & return if there is an error
	if (error_code)
	{
		// Check for disconnection errors
		std::set<boost::system::error_code>::iterator find_result = disconnect_errors.find(error_code);
		if (find_result != disconnect_errors.end())
		{
			if (error_code == boost::asio::error::operation_aborted)
			{
				// If we're waiting to shutdown, this is part of the normal process
				if(waiting_to_shutdown)
				{
					Logger::info("TCP server stopped listening for new connections", port, host);
				}
				else
				{
					Logger::warn("TCP accept was aborted", port, host);
				}
			}
			else
			{
				string message("TCP accept failed, disconnected: '" + error_code.message() + "'");
				Logger::warn(message, port, host);
				fire_disconnect(message);
			}
			return;
		}

		string message("Error accepting incoming connection: '" + error_code.message() + "'");
		Logger::error(message, port, host);
		fire_error(message);
		return;
	}

	// Initialize the socket options before we start using it
	init_socket(connection);

	// Log that we've successfully accepted a new connection, and fire the 'onconnect' event
	string message("TCP server accepted new connection from " + connection->remote_endpoint().address().to_string() + " port "
			+ boost::lexical_cast<string>(connection->remote_endpoint().port()));
	Logger::info(message, port, host);
	fire_connect();

	if (connection.get())
		connection->async_receive(boost::asio::buffer(receive_buffer),
				boost::bind(&TcpServer::receive_handler, this, _1, _2, connection, host, port));

	// Start listening for new connections, if we're not waiting to close
	if (!waiting_to_shutdown)
	{
		start_listening();
	}
}
예제 #6
0
파일: main.c 프로젝트: Zabrane/shim
int
main(int argc, char **argv)
{
	struct event_base *base;
	struct evdns_base *dns = NULL;
	int opt;
	const char *laddr, *lport;

	init_socket_stuff();

	base = event_base_new();
#ifndef DISABLE_DIRECT_CONNECTIONS
	dns = evdns_base_new(base, 1);
#endif
	log_set_file(NULL);

	laddr = DEFAULT_LISTEN_ADDR;
	lport = DEFAULT_LISTEN_PORT;

	while ((opt = getopt(argc, argv, "l:p:Vvq")) >= 0) {
		switch (opt) {
		case 'l':
			laddr = optarg;
			break;
		case 'p':
			lport = optarg;
			break;
		case 'V':
			printf("%s\n", PACKAGE_STRING);
			exit(1);
		case 'v':
			increase_log_verbosity();
			break;
		case 'q':
			decrease_log_verbosity();
			break;
		default:
			usage();
		}
	}

	argc -= optind;
	argv += optind;

	if (argc)
		set_socks_server(argv[0]);
	start_listening(base, dns, laddr, lport);
	event_base_dispatch(base);

	return 0;	
}
예제 #7
0
void ServerOSCThread::start_listening()
{
    try{
        ServerPacketListener listener(server);
        mux.AttachSocketListener(this->receiveSocket,&listener);
        qDebug() << "press ctrl-c to end";
        mux.RunUntilSigInt();
        exec();
    }
    catch(...)
    {
        qDebug() << "Some king of network error, trying to restart the listening thread...";
        start_listening();
    }
}
예제 #8
0
파일: util.c 프로젝트: amirsalah/cs2007
int start_listening_host(const char *host, int port)
{
  struct hostent *he = gethostbyname(host);
  struct in_addr ip;
  if (NULL == he) {
    fprintf(stderr,"%s: %s\n",host,hstrerror(h_errno));
    return -1;
  }

  if (4 != he->h_length) {
    fprintf(stderr,"%s: unknown address type (length %d)\n",host,he->h_length);
    return -1;
  }

  ip = *((struct in_addr*)he->h_addr_list[0]);
  return start_listening(ip,port);
}
예제 #9
0
파일: cdnwsh.c 프로젝트: claytondus/cdnwsh
int main(int argc, char *argv[]) {

	(void)argc;
	(void)argv;

	sh_err svr_err = start_listening();

	if(svr_err >=0) {
		printf("\nServer now running on port %s\n",SVR_PORT);
	} else {
		printf("\n%s",err_str(svr_err));
	}
	fflush(stdout);
	sh_err run_err = run();

	return run_err;
}
예제 #10
0
std::string& RadarServer::get_request(void)
{
	transmit_buffer.clear();
	if (sock_client > 0)
		finalize_client();
	if ((sock_listen < 0) && !start_listening()) {
		DERR	<< "listener socket invalid, "
			<< "restarting in some seconds..." << std::endl;
		sleep(5);
	} else if (accept_client()) {
		if (sock_getcmd())
			shutdown(sock_client, SHUT_RD);
		else
			finalize_client();
	}
	return transmit_buffer;
}
예제 #11
0
파일: discovery.c 프로젝트: ccpgames/wine
static BOOL start_listening_on_all_addresses(messageStorage *msgStorage, ULONG family)
{
    IP_ADAPTER_ADDRESSES *adapterAddresses = NULL, *adapterAddress;
    ULONG bufferSize = 0;
    LPSOCKADDR sockaddr;
    DWORD addressLength;
    char address[64];
    BOOL ret = FALSE;
    ULONG retVal;

    retVal = GetAdaptersAddresses(family, 0, NULL, NULL, &bufferSize); /* family should be AF_INET or AF_INET6 */
    if (retVal != ERROR_BUFFER_OVERFLOW) goto cleanup;

    /* Get size of buffer for adapters */
    adapterAddresses = (IP_ADAPTER_ADDRESSES *)heap_alloc(bufferSize);
    if (adapterAddresses == NULL) goto cleanup;

    /* Get list of adapters */
    retVal = GetAdaptersAddresses(family, 0, NULL, adapterAddresses, &bufferSize);
    if (retVal != ERROR_SUCCESS) goto cleanup;

    for (adapterAddress = adapterAddresses; adapterAddress != NULL; adapterAddress = adapterAddress->Next)
    {
        if (msgStorage->numThreadHandles >= MAX_LISTENING_THREADS)
        {
            ret = TRUE;
            goto cleanup;
        }

        if (adapterAddress->FirstUnicastAddress == NULL) continue;

        sockaddr = adapterAddress->FirstUnicastAddress->Address.lpSockaddr;
        addressLength = sizeof(address);
        WSAAddressToStringA(sockaddr, adapterAddress->FirstUnicastAddress->Address.iSockaddrLength, NULL, address, &addressLength);

        start_listening(msgStorage, adapterAddress->FirstUnicastAddress->Address.lpSockaddr->sa_family == AF_INET ? SEND_ADDRESS_IPV4 : SEND_ADDRESS_IPV6, address);
    }

    ret = TRUE;

cleanup:
    heap_free(adapterAddresses);
    return ret;
}
예제 #12
0
파일: main.c 프로젝트: sgiurgiu/smlaunch
int main(int argc, char** argv)
{
	signal(SIGINT,signal_handler);//TODO: OBSOLETE, use sigaction
	signal(SIGTERM,signal_handler);
	openlog("smlaunch",LOG_CONS|LOG_PID,LOG_USER);	
	setlogmask(LOG_DEBUG);
	sm_log(LOG_INFO,"starting %s server\n",argv[0]);
	player_init();
	
	//TODO: make this an option of some kind
	//actually...not setting this will be an option
	//daemon(0,0);
	
	setup_server();
	start_listening();
	
	exit_program(EXIT_SUCCESS);//most likely will never be reached	
	return (0);
}
예제 #13
0
Server::Server(PCSTR port, unsigned buflen, Game* game)
			:m_port(port), m_buflen(buflen), m_data_buffer(new char[m_buflen]), m_game(game) {
	m_state = NOT_STARTED;
	int iResult = WSAStartup(MAKEWORD(2,2), &m_wsaData);
	if (iResult) {
		printf("WSAStartup failed: %d\n", iResult);
		m_state = IN_ERROR_STATE;
	}

	if (m_state != IN_ERROR_STATE) {
		setup_addrinfo();
	}

	if (m_state != IN_ERROR_STATE) {
		start_listening();
	}

	if (m_state != IN_ERROR_STATE) {
		m_state = STARTED;
	}
}
예제 #14
0
파일: echo1.c 프로젝트: amirsalah/cs2007
int main(int argc, char **argv)
{
  int port;
  int listensock;
  int sock;
  int bufsize;

  setbuf(stdout,NULL);
  signal(SIGPIPE,SIG_IGN);

  if (3 > argc) {
    fprintf(stderr,"Usage: echo1 <port> <bufsize>\n");
    return -1;
  }

  port = atoi(argv[1]);
  bufsize = atoi(argv[2]);

  check(0 <= (listensock = start_listening(port)));
  printf("ready\n");

  while (0 <= (sock = accept_connection(listensock))) {
    int dalloc = bufsize;
    int dsize = 0;
    char *data = malloc(bufsize);
    int reading = 1;

    while (reading || (0 < dsize)) {

      fd_set readfds;
      fd_set writefds;
      int n;

      FD_ZERO(&readfds);
      FD_ZERO(&writefds);
      if (reading)
        FD_SET(sock,&readfds);
      if (0 < dsize)
        FD_SET(sock,&writefds);

      check(1 <= select(sock+1,&readfds,&writefds,NULL,NULL));

      if (FD_ISSET(sock,&writefds)) {
        check (0 <= (n = write(sock,data,dsize)));
        memmove(&data[0],&data[n],dsize-n);
        dsize -= n;
      }

      if (FD_ISSET(sock,&readfds)) {
        check (0 <= (n = read(sock,&data[dsize],bufsize)));
        if (0 == n) {
          reading = 0;
        }
        else {
          dsize += n;
          if (dalloc < dsize+bufsize) {
            dalloc = dsize+bufsize;
            data = realloc(data,dalloc);
          }
        }
      }
    }

    check(0 == close(sock));
    free(data);
    printf("Connection closed\n");
  }

  return 0;
}
예제 #15
0
파일: main.c 프로젝트: dsqmoore/dsra
int main(int argc, const char * argv[])
{
	int list = 0;
	int i;
	const char * port = "4575";
	const char * device = NULL;
	for (i=1; i<=argc; i++)
	{
		if (!argv[i]) continue;
		if ((strcmp(argv[i],"-h")==0)||(strcmp(argv[i],"--help")==0)||(strcmp(argv[i],"-?")==0))
			usage();
		if (strncmp(argv[i],"-p=",3)==0)
		{
			port = argv[i]+3;
			continue;
		}
		if (strncmp(argv[i],"--port=",7)==0)
		{
			port = argv[i]+7;
			continue;
		}
		if (strcmp(argv[i],"-v")==0)
		{
			verbose = 1;
			continue;
		}
		if (strcmp(argv[i],"-l")==0)
		{
			list = 1;
			continue;
		}
		
		if (strcmp(argv[i],"--list")==0)
		{
			list = 1;
			continue;
		}
		if (strncmp(argv[i],"--dev=",6)==0)
		{
			device = argv[i]+6;
			continue;
		}
		printf("Unknown option: %s\n",argv[i]);
		usage();
	}
    if (init_audio()!=0)
        return 1;
	if ((dev=device_for_string(device))==-1)
	{
		fprintf(stderr,"Unknown device \"%s\"\n",device?device:"");
		cleanup_audio();
		return 1;
	} else {
		fprintf(stderr,"Using device \"%s\"\n",Pa_GetDeviceInfo(dev)->name);
	}
	if (list)
	{
		list_devices();
		cleanup_audio();
		return 0;
	}
	if (start_listening(port)!=0)
	{
		cleanup_audio();
		return 1;
	}
    cleanup_audio();
	return 0;
}      
예제 #16
0
int main(int argc, const char* argv[])
{
    int myport = parse_options(argc, argv);
    
    std::cout << "Reading genomes...\n";
    std::cout.flush();
    initializeGenomeSystem();
    std::cout << "Reading solution...\n";
    initializeSolutionSystem();
    std::cout << "Got solutions\n";
    
    try {
        int listen_socket = start_listening(myport);
        
        fd_set mask, dummy_mask, temp_mask;
        
        FD_ZERO(&mask);
        FD_ZERO(&dummy_mask);
        FD_SET(listen_socket, &mask);
        
        std::set<int> sockets;
        
        for(;;)
        {
            temp_mask = mask;
            int num = select(FD_SETSIZE, &temp_mask, &dummy_mask, &dummy_mask, NULL);
            if( num > 0 )
            {
                if( FD_ISSET(listen_socket, &temp_mask) )
                {
                    int new_socket = accept(listen_socket, 0, 0);
                    FD_SET(new_socket, &mask);
                    sockets.insert(new_socket);
                }
                
                for( std::set<int>::iterator iter = sockets.begin(); iter != sockets.end(); ++iter )
                {
                    int cur_sock = *iter;
                    if( FD_ISSET(cur_sock, &temp_mask) )
                    {
                        msgpack::unpacker unpack;
                        readBuffer(cur_sock, unpack);
                    
                        message_id_t msg_id;
                        read(unpack, msg_id);
                        switch( msg_id )
                        {
                            case STORE_NEW_GENOME_ID:
                                handle_new_genome(cur_sock, unpack);
                                break;
                            case STORE_NEW_DATA_ID:
                                handle_new_data(cur_sock, unpack);
                                break;
                            case STORE_NEW_SOLUTION_ID:
                                handle_new_solution(cur_sock, unpack);
                                break;
                            case STORE_QUERY_BY_ID_ID:
                                handle_query_by_id(cur_sock, unpack);
                                break;
                            case STORE_QUERY_BY_COND_ID:
                                handle_query_by_cond(cur_sock, unpack);
                                break;
                            case STORE_GENOME_INFO_QUERY_ID:
                                handle_genome_info_query(cur_sock, unpack);
                                break;
                            case STORE_GENOME_CONTENT_QUERY_ID:
                                handle_genome_content_query(cur_sock, unpack);
                                break;
                            case STORE_MAX_SOL_REQUEST_ID:
                                handle_max_solution(cur_sock, unpack);
                                break;
                            case GENOME_LIST_REQUEST_ID:
                                handle_genome_list(cur_sock, unpack);
                                break;
                            default:
                                std::cerr << "Unknown message type: " << msg_id << " from socket " << cur_sock << "\n";
                        }
                    }
                }
            }
        }
        
    }
    catch( const std::exception& err )
    {
        std::cerr << err.what() << "\n";
        exit(-1);
    }
    
    return 0;
}
예제 #17
0
파일: roxanne_db.c 프로젝트: rtyler/Roxanne
int main(int argc, char* argv[]) {

  struct sockaddr incoming;
  socklen_t addr_size = sizeof(incoming); 
  int listen_fd, accept_fd;
  char* port = "4080";
  char* host = "::1";
  char keydb_file[4096];
  char keydb_freelist[4096];
  char db_file[4096];
  char idx_file[4096];
  char block_bitmap_file[4096];
  int chld;
  int i;
  int ch;


  // parse our cmd line args
  while ((ch = getopt(argc, argv, "d:h:p:")) != -1) {
    switch (ch) {

      case 'd':
        sprintf(DATA_HOME, "%s", optarg);
        break;

      case 'h':
        host = optarg;
        break;

      case 'p':
        port = optarg;
        break;

     case '?':

     default:
       usage(argv[0]);
     }
  }
  argc -= optind;
  argv += optind;

  sprintf(keydb_file, "%s/keydb", DATA_HOME);
  sprintf(keydb_freelist, "%s/keydb_freelist", DATA_HOME);
  sprintf(db_file, "%s/db", DATA_HOME);
  sprintf(idx_file, "%s/idx", DATA_HOME);
  sprintf(block_bitmap_file, "%s/block_bitmap", DATA_HOME);
  

  // Used to coordinate exclusive access to the block bitmap.
  if ((BLOCK_BITMAP_LOCK = sem_open("block_bitmap_lock", O_CREAT, 0666, 1)) == SEM_FAILED) {
    perror("semaphore init failed");
    exit(-1);
  }
  sem_post(BLOCK_BITMAP_LOCK);

  // Used to coordinate exclusive access to the bitmap array of keydb locks.
  if ((KEYDB_LOCK = sem_open("keydb_lock", O_CREAT, 0666, 1)) == SEM_FAILED) {
    perror("semaphore init failed");
    exit(-1);
  }
  sem_post(KEYDB_LOCK);

  // This is used to safely append to the end of the index file.
  if ((IDX_APPEND_LOCK = sem_open("idx_lock", O_CREAT, 0666, 1)) == SEM_FAILED) {
    perror("semaphore init failed");
    exit(-1);
  }
  sem_post(IDX_APPEND_LOCK);

  // Used to coordinate exclusive access to the bitmap array of hash key space locks. 
  if ((HASHBUCKET_LOCK = sem_open("hashbucket_lock", O_CREAT, 0666, 1)) == SEM_FAILED) {
    perror("semaphore init failed");
    exit(-1);
  }
  sem_post(HASHBUCKET_LOCK);

  // Memory-map our block bitmap file creating it if necessary.
  // The block bitmap keeps track of free/busy blocks in the db file.
  if ((BLOCK_BITMAP_FD = open(block_bitmap_file, O_RDWR | O_CREAT, 0666)) == -1) {
    fprintf(stderr, "Couldn't open block bitmap file %s\n", block_bitmap_file);
    perror(NULL);
    exit(-1);
  }
  if ((SHM_BLOCK_BITMAP = mmap((caddr_t)0, BLOCK_BITMAP_BYTES, PROT_READ | PROT_WRITE, MAP_SHARED, BLOCK_BITMAP_FD, 0)) == MAP_FAILED) {
    perror("Problem mmapping the block bitmap");
    exit(-1);
  }
  
  // A mem-mapped block of anonymous memory used to lock parts of the database index.
  // See hash_write_lock() and hash_write_unlock()
  if ((SHM_HASHBUCKET_BITMAP = mmap((caddr_t)0, ((1<<HASH_BITS)/8), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0)) == MAP_FAILED) {
    perror("Problem mmapping the hash bitmap");
    exit(-1);
  }
  
  // A mem-mapped block of anonymous memory used to lock parts of the keydb tree.
  // See keydb_lock() and keydb_unlock()
  if ((SHM_KEYDB_BITMAP = mmap((caddr_t)0, ((KEYDB_LOCKS)/8), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0)) == MAP_FAILED) {
    perror("Problem mmapping the keydb lock bitmap");
    exit(-1);
  }
  
  // register a function to reap our dead children
  signal(SIGCHLD, sigchld_handler); 

  // Register a function to kill our children.
  // We'll unregister this function in our children.
  signal(SIGTERM, sigterm_handler_parent); 

  // Open our database file
  if ((DB_FD = open(db_file, O_RDWR | O_CREAT, 0666)) == -1) {
    fprintf(stderr, "Couldn't open database file named %s\n", db_file);
    perror(NULL);
    exit(-1);
  }

  // Open our keydb file
  if ((KEYDB_FD = open(keydb_file, O_RDWR | O_CREAT, 0666)) == -1) {
    fprintf(stderr, "Couldn't open key file named %s\n", keydb_file);
    perror(NULL);
    exit(-1);
  }

  // Open our keydb freelist
  if ((KEYDB_FREELIST_FD = open(keydb_freelist, O_RDWR | O_CREAT, 0666)) == -1) {
    fprintf(stderr, "Couldn't open key file named %s\n", keydb_freelist);
    perror(NULL);
    exit(-1);
  }

  // Open our index file
  if ((IDX_FD = open(idx_file, O_RDWR | O_CREAT, 0666)) == -1) {
    fprintf(stderr, "Couldn't open index file named %s\n", idx_file);
    perror(NULL);
    exit(-1);
  }

  // Demonize ourself.
  if ((chld = fork()) != 0 ) {printf("%d\n",chld); return(0);};

  // Start listening
  if ((listen_fd = start_listening(host, port, BACKLOG)) == -1) {
    fprintf(stderr, "Call to start_listening failed\n");
    perror(NULL);
    exit(-1);
  }

  fprintf(stderr, "Started listening.\n");

  while (1) {  

    // Accept new connection.
    if ((accept_fd = accept(listen_fd, (struct sockaddr *)&incoming, &addr_size)) == -1) {
      fprintf(stderr, "Call to accept() failed.\n");
      return(-1);
    }

    fcntl(accept_fd, F_SETFD, O_NONBLOCK);

    // Start a child with the new connection.
    if ((chld = fork()) == 0 ){
      guts(accept_fd, listen_fd);
    } else {
      close(accept_fd);
    }

  } // while (1)

  return(0);

}
예제 #18
0
int main(int argc, char **argv)
{
    int port;
    int listensock;
    int sock;

    setbuf(stdout,NULL);
    memset(&recvbuf,0,sizeof(recvbuf));

    if (2 > argc) {
        fprintf(stderr,"Usage: msgserver <port>\n");
        return -1;
    }

    port = atoi(argv[1]);
    if (0 > (listensock = start_listening(port)))
        return -1;

    printf("Waiting for connection...\n");
    while (0 <= (sock = accept_connection(listensock))) {

        /* Reset the buffer size to 0 in case a previous connection closed without
           completing the last message. */
        recvbuf.size = 0;

        while (1) {
            int r;

            /* Allocate more memory for the receive buffer, if necessary */
            if (recvbuf.alloc < recvbuf.size+CHUNKSIZE) {
                recvbuf.alloc = recvbuf.size+CHUNKSIZE;
                recvbuf.data = realloc(recvbuf.data,recvbuf.alloc);
            }

            /* Read the next chunk of data */
            r = read(sock,&recvbuf.data[recvbuf.size],CHUNKSIZE);
            if (0 > r) {
                /* Read error */
                perror("read");
                close(sock);
                break;
            }
            else if (0 == r) {
                /* Clean disconnect */
                if (0 < recvbuf.size)
                    fprintf(stderr,"Client disconnected without completing message\n");
                close(sock);
                break;
            }
            else {
                /* We have some data... process all of the completed messages we've
                   received so far. It is possible that the call to read may have
                   obtained the data from a message that was incomplete the last
                   time round, so this will be processed too. */
                recvbuf.size += r;
                process_incoming();
            }
        }
        printf("Client closed connection\n");
    }

    return 0;
}
예제 #19
0
void ServerOSCThread::run() {
    start_listening();
}