Ejemplo n.º 1
0
/*
 * 必须在服务器端调用
 */
int Socket::WaitClient()
{
    // 初始化文件描述符集合 initialize file descriptor set
    FD_ZERO(&_sockets);
    // 把Sock_fd加入到文件描述符集合
    FD_SET(_server_sock, &_sockets);
    _maxsock = _socks[_conn_amount-1];

    // 把活动的socket的句柄加入到文件描述符集合中
    for (int i = 0; i < _conn_amount; i++) {
        FD_SET(_socks[i], &_sockets);
    }
    
    // 设置为永久阻塞,因此会阻塞掉调用线程。
    int ret = select(_maxsock + 1, &_sockets, NULL, NULL, NULL);
    if (ret <= 0) {
        perror("select error!");
        return -1;
    }

    // 轮询各个文件描述符(socket)
    for (int i = 0; i < _conn_amount; i++) {
        if (FD_ISSET(_socks[i], &_sockets)) {
            if (_socks[i] == _server_sock) {
                AcceptClient();
            } else {
                ReadClient(i);
            }
        }
    }
    
    return 0;
}
Ejemplo n.º 2
0
int CNetConsole::Update()
{
	NETSOCKET Socket;
	NETADDR Addr;

	if(net_tcp_accept(m_Socket, &Socket, &Addr) > 0)
	{
		// check if we just should drop the packet
		char aBuf[128];
		if(NetBan() && NetBan()->IsBanned(&Addr, aBuf, sizeof(aBuf)))
		{
			// banned, reply with a message and drop
			net_tcp_send(Socket, aBuf, str_length(aBuf));
			net_tcp_close(Socket);
		}
		else
			AcceptClient(Socket, &Addr);
	}

	for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++)
	{
		if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ONLINE)
			m_aSlots[i].m_Connection.Update();
		if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR)
			Drop(i, m_aSlots[i].m_Connection.ErrorString());
	}

	return 0;
}
Ejemplo n.º 3
0
void Server::AcceptClients()
{
  sigset_t mask;
  sigfillset(&mask);
  sigdelset(&mask, SIGUSR1);

  for (auto& pfd : fds) pfd.revents = 0;
  
  int n = poll(fds.data(), fds.size(), 100);
  if (n < 0)
  {
    logs::Error("Server select failed: %1%", util::Error::Failure(errno).Message());
    // ensure we don't poll rapidly on repeated select failures
    boost::this_thread::sleep(boost::posix_time::milliseconds(100));
  }
  else
  {
    // last pullfd is interrupt pipe
    if (fds.back().revents & POLLIN)
    {
      interruptPipe.Acknowledge();
      HandleTasks();
    }
    
    for (auto it = fds.begin(); it != fds.end() - 1; ++it)
    {
      if (it->revents & POLLIN)
        AcceptClient(servers.at(it->fd));
    }
  }
}
Ejemplo n.º 4
0
void Server::HandleEvent(int fd, FileEventType event) {
  std::cout << "[" << fd << "," << (int)event << "]" << std::endl;

  if (fd == listen_fd_) {
    AcceptClient();
  } else {
    Client *client = clients_[fd];

    if (client == NULL) {
      return;
    }

    char buf[256] = "";
    int received = recv(fd, buf, sizeof(buf)-1, 0);

    if (received <= 0) {
      Disconnect(client);
    } else {
      if (client_manager_) {
        client->AddBuffer(buf, received);
        if (client_manager_->HandleBuffer(client) ==
            ClientManagerInterface::kInvalid) {
          Disconnect(client);
        }
      }
    } 
  }
}
Ejemplo n.º 5
0
void Listen::Tcp() {
  try {
    ListenOn(*listener_tcp_);
    while (listener_tcp_ && listener_tcp_->IsValid()) {
      AcceptClient();
    }
  } catch (NetworkException e) {
    Display::Console::PrintError(e.what());
    Error::LogToFile(e.what(), e.code(), e.message());
  }
}
Ejemplo n.º 6
0
Archivo: worker.c Proyecto: jxva/miaoox
int InitWorker(Worker* w) {
    worker = w;
    worker->stop = 0;
    worker->max_event_num = MAX_EVENT_NUM;

    if (worker == NULL){
        mLog(MSG_WARNING, "Memmory allocate failed when creating Worker.");
        return -1;
    }
    if ((worker->poll = evCreateEventLoop(worker->max_event_num)) == NULL) {
        mLog(MSG_WARNING, "Memmory allocate failed when creating Event-loop.");
        return -1;
    }
    AcceptClient();
    InitWorkerSignals();

    while (!worker->stop) {
        evProcessEvents(worker->poll, EV_IO_EVENTS);
    }

    return 0;
}
Ejemplo n.º 7
0
void TCPServerListener::Listen() {
  _RPT0(0, "TCPServer: Starting to Listen\n");
  fd_set test_set;
  fd_set test_set2;

  timeval t;
  t.tv_sec = 1;  // Shutdown test every second
  t.tv_usec = 0;  

  timeval t2; // Always nonblock
  t2.tv_sec = 0;
  t2.tv_usec = 0;



  ClientConnection s_list[FD_SETSIZE];
  int i;
  if (lzo_init() != LZO_E_OK) { 
    env->ThrowError("TCPServer: Could not initialize LZO compression library!");
  }
  ServerReply s;

  for (i = 0; i < FD_SETSIZE ; i++)
    memset(&s_list[i], 0, sizeof(ClientConnection));

  while (!shutdown) {
    // Attempt to Accept an incoming request

    FD_ZERO(&test_set);
    FD_SET(m_socket, &test_set);
    select(0, &test_set, NULL, NULL, &t2);

    if (FD_ISSET(m_socket, &test_set)) {
      AcceptClient(accept( m_socket, NULL, NULL ), &s_list[0]);
      _RPT0(0, "TCPServer: Client Connected.\n");
    }


    FD_ZERO(&test_set);
    FD_ZERO(&test_set2);

    bool anyconnected = false;
    for (i = 0; i < FD_SETSIZE; i++) {
      if (s_list[i].isConnected) {
        FD_SET(s_list[i].s, &test_set);
        if (s_list[i].isDataPending) {
          FD_SET(s_list[i].s, &test_set2);
        }
        anyconnected = true;
      }
    }

    if (!anyconnected) {
      Sleep(100);
      continue;
    }

    select(0, &test_set, &test_set2, NULL, &t);
    bool request_handled = false;

    for (i = 0; i < FD_SETSIZE; i++) {
      s.dataSize = 0;
      if (s_list[i].isConnected) {
        if (FD_ISSET(s_list[i].s, &test_set) && (!s_list[i].isDataPending)) {

          request_handled = true;
          TCPRecievePacket* tr = new TCPRecievePacket(s_list[i].s);

          _RPT1(0, "TCPServer: Bytes Recv: %ld\n", tr->dataSize );

          if (!tr->isDisconnected) {
            s.dataSize = 0;
            s.client = &s_list[i];  // Add client info to serverreply.
            Receive(tr, &s);

            if (s.dataSize > 0) {
              SendPacket(&s_list[i], &s);
            } // end if datasize > 0

          }
          else { // isDisconnected
            _RPT0(0, "TCPServer: Connection Closed.\n");
            closesocket(s_list[i].s);
            s_list[i].reset();
          }
          delete tr;
        } // end if fd is set
      } // end if list != null
    } // end for i


    for (i = 0; i < FD_SETSIZE; i++) {
      if (FD_ISSET(s_list[i].s, &test_set2) && s_list[i].isDataPending ) {
        request_handled = true;
        SendPendingData(&s_list[i]);
      } // end if isDataPending
    }

    if (!request_handled) {
      t.tv_usec = 100000;  // If no request we allow it to wait 100 ms instead.
      if (prefetch_frame > 0) {
        _RPT1(0, "TCPServer: Prerequesting frame: %d", prefetch_frame);
        child->GetFrame(prefetch_frame, env);  // We are idle - prefetch frame
        prefetch_frame = -1;
      }
    } else {
      t.tv_sec  = 0;
      t.tv_usec = 1000; // Allow 1ms before prefetching frame.
    }
  } // while !shutdown
  for (i = 0; i < FD_SETSIZE; i++) {
    if (s_list[i].isConnected) {
      closesocket(s_list[i].s);
    }
  }

  closesocket(m_socket);
  WSACleanup();
  thread_running = false;
  _RPT0(0, "TCPServer: Client thread no longer running.\n");
}
Ejemplo n.º 8
0
void Server(void)
{
    int serverSocketDescriptor, clientSocketDescriptor;
    fd_set readset;
    int descTableSize = getdtablesize();
    int i;

    SetSignal(SIGURG, &OOBSignalHandler);

    serverSocketDescriptor = StartServer("127.0.0.1", 6660, "tcp");
    info.info_count = 0;
    while(1)
    {
        FD_ZERO(&readset);
        FD_SET(serverSocketDescriptor, &readset);

        for (i=0; i<info.info_count; i++)
        {
            FD_SET(info.connectionInfo[i].socket, &readset);
            printf("Added Socket %d.\n", info.connectionInfo[i].socket);
        }

        if (select(descTableSize, &readset, NULL, NULL, NULL) == -1)
        {
            puts("Select failed.");
            CloseAllSockets();
            return;
        }

        if (FD_ISSET(serverSocketDescriptor, &readset))
        {
            clientSocketDescriptor = AcceptClient(serverSocketDescriptor);
            if (clientSocketDescriptor == -1)
            {
                puts("AcceptClient failed.");
            }
            printf("Client connected at socket %d.\n", clientSocketDescriptor);

            if (Preparation(clientSocketDescriptor) == -1)
            {
                puts ("Preparation failed.");
                CloseAllSockets();
                return;
            }
            SetSocketOwner(clientSocketDescriptor);
            fcntl(clientSocketDescriptor, F_SETFL, O_NONBLOCK);

        }
        else
      {


      for (i=0; i<info.info_count; i++)
        {
            if (FD_ISSET(info.connectionInfo[i].socket, &readset))
            {
                ServerProcessing(&info.connectionInfo[i]);
            }
        }


      }



    }
    return;
}
Ejemplo n.º 9
0
void TCPServer<SessionClass>::Run()
{
   while (true)
   {
      // State machine to handle the server
      switch (State)
      {
      case SRVR_NOT_STARTED:
         // Idle state waits for the server to be started
         if (ServerIsActive)
         {
            State = SRVR_BIND;
         }
         break;

      case SRVR_BIND:

         // Create, bind, and listen the listener socket
         ServerIsActive = InitListener();

         if (ServerIsActive)
         {
            // Poll each of the client sessions
            PollClients();
            State = SRVR_LISTENING;
         }
         else
         {
            // Disconnect all connected clients
            DisconnectAll();
            State = SRVR_NOT_STARTED;
         }

         break;

      case SRVR_LISTENING:

         if (!ServerIsActive)
         {
            // Disconnect all connected clients
            DisconnectAll();
            State = SRVR_NOT_STARTED;
         }
         else
         {
            // Accept incoming connections
            AcceptClient();

            // Poll each of the client sessions
            PollClients();
         }

         // If the number of connected clients reaches the max, stop listening
         if (NumActiveSessions() >= MaxSessions)
         {
            close(ListenerSocket);
            State = SRVR_FULL;
         }

         break;

      case SRVR_FULL:

         if (!ServerIsActive)
         {
            // Disconnect all connected clients
            DisconnectAll();
            State = SRVR_NOT_STARTED;
         }
         else
         {
            // Poll each of the client sessions
            PollClients();
         }

         // If the number of connected clients is less than the max, then bind and listen for connections again
         if (NumActiveSessions() < MaxSessions)
         {
            State = SRVR_BIND;
         }

         break;

      default:
         ServerIsActive = false;
         ServerAddress = 0;
         ServerPort = 0;
         State = SRVR_NOT_STARTED;
         break;

      }

      Delay(POLL_INTERVAL_MS);
   }
}
Ejemplo n.º 10
0
//---------------------------------------------------------------------------
void __fastcall TClientSockThread::Execute()
{
	AcceptClient();
	//---- Place thread code here ----
}