#
# You should have received a copy of the GNU General Public License
# along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA

"http://laurentszyster.be/blog/tutorial-one/"

# A Simple Client

from allegra import async_loop, async_chat, collector, async_client

dispatcher = async_chat.Dispatcher()
if async_client.connect(dispatcher, ("66.249.91.99", 80), 3):
    dispatcher.async_chat_push("GET / HTTP/1.0\r\n" "\r\n")
    collector.bind(dispatcher, collector.LOGINFO)
async_loop.dispatch()


# Adding Features

from allegra import finalization, async_limits, synchronized

dispatcher = async_chat.Dispatcher()
if async_client.connect(dispatcher, ("66.249.91.99", 80), 3):
    dispatcher.async_chat_push("GET / HTTP/1.1\r\n" "Host: 66.249.91.99\r\n" "Connection: keep-alive\r\n" "\r\n")
    collector.bind(dispatcher, synchronized.File_collector("response.txt"))
    async_limits.limit_recv(dispatcher, 3, 1, (lambda: 1 << 13))
    dispatcher.finalization = lambda finalized: finalized.log('bytes in="%d"' % finalized.ac_in_meter)
    del dispatcher
async_loop.dispatch()
from allegra import (loginfo, async_loop, async_chat, collector, tcp_client)

dispatcher = async_chat.Dispatcher()
if tcp_client.connect(dispatcher, ("planetpython.org", 80), 3.0):
    dispatcher.async_chat_push('GET /rss20.xml HTTP/1.0\r\n'
                               'Host: planetpython.org\r\n'
                               'Accept: text/xml; charset=UTF-8\r\n'
                               '\r\n')
    collector.bind(dispatcher, collector.DEVNULL)
del dispatcher
async_loop.dispatch()


#
# a convenience to ...
#
def getXMLUTF8(dispatcher, host, path, version="1.0", connection="Keep-Alive"):
    dispatcher.async_chat_push('GET %s HTTP/%s\r\n'
                               'Host: %s\r\n'
                               'Accept: text/xml; charset=UTF-8\r\n'
                               'Connection: %s\r\n'
                               '\r\n' % (path, version, host, connection))
    return dispatcher


#
# ... use Connections and HTTP/1.0
#
connections = tcp_client.Connections(0.3, 0.1)
for host, path in [
    ("planetpython.org", "/rss20.xml"),