[Home]BoostSocket/ServerExample

BOOST WIKI | BoostSocket | RecentChanges | Preferences | Page List | Links List

Server Example

Exception and error handling not shown

  socket_base::initialise();

  typedef std::map<socket_base, boost::sockets::ip4::address> Clients;
  Clients clients;

  ip4::address addr;
  addr.port(3234);
  addr.hostname("localhost");

  ip4::tcp_protocol protocol;

  socket_option_non_blocking non_block(true);

  acceptor_socket listening_socket;
  listening_socket.open(protocol,addr,6);

  boost::sockets::socket_set master_set;
  master_set.add(listening_socket.socket());

  while (true)
  {
    boost::sockets::socket_set active_set;
    active_set=master_set;

    if (::select(active_set.width(),
                 active_set.fdset(),
                 0,
                 0,
                 0)==socket_error)
    {
      check_error();
      return;
    }

    boost::sockets::socket_set::iterator
      i=active_set.begin(),
      i_end=active_set.end();

    for (; i!=i_end; ++i)
    {
      if (*i==listening_socket.socket().socket())
      {
        while (true)
        {
          //! this is our acceptor socket
          ip4::address client;
          socket_base accepted_socket=listening_socket.accept(client);
          if (accepted_socket.isValid())
          {
            accepted_socket.ioctl(non_block);
            master_set.add(accepted_socket);
            clients.insert(std::make_pair(accepted_socket, client));
          }
          else
            break;
        }
      }
      else
      {
        // these are our data sockets
        socket_base data_socket(*i);

        ip4::address& client=clients[data_socket];
        boost::sockets::basic_socket_stream<char> ss(data_socket);

        while (!ss.eof() && !ss.fail())
        {
          ss >> str;
          if (!ss.fail())
            BOOST_MESSAGE(str);
        }
        if (ss.eof())
        {
          master_set.remove(data_socket);
          clients.erase(data_socket);
          data_socket.close();
        }
      }
    }
  }

BOOST WIKI | BoostSocket | RecentChanges | Preferences | Page List | Links List
Edit text of this page | View other revisions
Last edited December 18, 2004 12:26 pm (diff)
Search:
Disclaimer: This site not officially maintained by Boost Developers