Sockets?

I was wondering why make an non-blocking socket? What advantage does it provide in comparison to a blocking socket? And you could give me an example of when a non-blocking socket would be more useful.
closed account (3hM2Nwbp)
I can't compile this from where I'm at right now, and I'm going from memory, but it should give you a vague idea. There are many parts missing that aren't relevant to the question (like destruction for example).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include<boost/asio.hpp>

typedef boost::asio::ip::tcp::socket Socket;
typedef boost::asio::ip::tcp::acceptor Acceptor;

class TCPAcceptor
{
  private:
    Acceptor* _acceptor;
    unsigned short _port;
  public:
    TCPAcceptor(boost::asio::io_service& io_svc, unsigned short port)
     : _port(port), _acceptor(new Acceptor(io_svc))
    {
      boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
      _acceptor->open(endpoint.protocol());
      _acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
      _acceptor->bind(endpoint);
      _acceptor->listen();
    }

    void start(void)
    {
        Socket* socket = new Socket(io_svc);
        this->_acceptor->async_accept(socket, boost::bind(&TCPAcceptor::onAccept, this, socket, boost::asio::placeholders::error));
    }

    void onAccept(Socket* socket, boost::system::error_code& error)
    {
      if(error)
      {
        std::cout << "Error: " << error;
        delete socket;
      }
      else
      {
         std::cout << "Accepted Socket: " << socket << std::endl;
      }
      Socket* nextSocket = new Socket(io_svc);
        this->_acceptor->async_accept(nextSocket, boost::bind(&TCPAcceptor::onAccept, this, nextSocket, boost::asio::placeholders::error));
    }
};

boost::asio::io_service io_svc;


int main()
{
  TCPAcceptor acceptor(io_svc, 12345);
  acceptor.start();
  for(;;)
  {
    try
    {
        io_svc.run();
        break;
    }
    catch(...)
    {
      std::cout << "Error: " << error.message() << std::endl;
    }
  }
  return 0;
}
Last edited on
Without going into actual code....

For a couple reasons. First, say you are writing a server that can handle multiple connections. If your server blocks on a write to one socket, then your server isn't going to service any of its other connections. If your server blocks on a read of a socket, same thing. These two things are particularly bad for security since one misbehaving client can take your server down -- it's a classic Denial of Service attack.

In general, the answer is because you need the server/process to remain responsive to other things while dealing with the socket.
Thanks, that summed it up perfectly.
Topic archived. No new replies allowed.