# File lib/rbot/ircbot.rb, line 863
  def mainloop
    while true
      begin
        quit if $interrupted > 0
        connect

        quit_msg = nil
        while @socket.connected?
          quit if $interrupted > 0

          # Wait for messages and process them as they arrive. If nothing is
          # received, we call the ping_server() method that will PING the
          # server if appropriate, or raise a TimeoutError if no PONG has been
          # received in the user-chosen timeout since the last PING sent.
          if @socket.select(1)
            break unless reply = @socket.gets
            @last_rec = Time.now
            @client.process reply
          else
            ping_server
          end
        end

      # I despair of this. Some of my users get "connection reset by peer"
      # exceptions that ARENT SocketError's. How am I supposed to handle
      # that?
      rescue SystemExit
        log_session_end
        exit 0
      rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
        error "network exception: #{e.pretty_inspect}"
        quit_msg = e.to_s
      rescue BDB::Fatal => e
        fatal "fatal bdb error: #{e.pretty_inspect}"
        DBTree.stats
        # Why restart? DB problems are serious stuff ...
        # restart("Oops, we seem to have registry problems ...")
        log_session_end
        exit 2
      rescue Exception => e
        error "non-net exception: #{e.pretty_inspect}"
        quit_msg = e.to_s
      rescue => e
        fatal "unexpected exception: #{e.pretty_inspect}"
        log_session_end
        exit 2
      end

      disconnect(quit_msg)

      log "\n\nDisconnected\n\n"

      quit if $interrupted > 0

      log "\n\nWaiting to reconnect\n\n"
      sleep @config['server.reconnect_wait']
    end
  end