from gi.repository import Gio, GLib

host = "www.google.com"
port = 80
path = "/"

mainloop = None
socket_client = None
conn = None

def on_connect (socket, result, data):
    global conn

    host, port, path = data
    conn = socket.connect_to_host_finish (result)
    
    handshake(host, port, path)
    
def handshake(host, port, path):
    message = "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n" % (path, host)
    stream = conn.get_output_stream ()
    stream.write (message, None)

    input_stream = conn.get_input_stream ()
    response = Gio.DataInputStream (base_stream=input_stream)
    
    status, resp_headers = read_headers (response)
    print status
    print resp_headers
    
    mainloop.quit()

def read_headers(stream):
    status = None
    headers = {}
    
    while True:
        line, length = stream.read_line_utf8 (None)
        if line == "\r\n" or line == "\r":
            break
        line = line.strip()
        if not status:
            status_info = line.split(" ", 2)
            status = int(status_info[1])
        else:
            kv = line.split(":", 1)
            if len(kv) == 2:
                key, value = kv
                headers[key.lower()] = value.strip().lower()
            else:
                raise Exception("Invalid header")
            
    return status, headers


if __name__ == "__main__":
    socket_client = Gio.SocketClient()
    socket_client.connect_to_host_async ("%s:%s" % (host, port), 80, Gio.Cancellable(), on_connect, (host, port, path))

    mainloop = GLib.MainLoop ()
    mainloop.run ()
