--------------------------------------------------- 
-- FBA Tutorials
--
-- Tutorial / 21 / Http Get With Tcp Sockets
--
--------------------------------------------------- 
--
-- This sample will show you how to fetch a string from a remote
-- file on a webserver using simple TCP socket connection.
--
-- Please be sure your device is connected to internet when
-- you test this application on it.
--
-- Note: In this tutorial, our test page on FBA website will return
-- just one line.
--
--------------------------------------------------- 

local sock=socket.tcp()
local waitheader = 0
local finalStr = "Waiting string from HTTP request.."

-- just to test mime encoding, encode a string with base64
local mime = require("mime")
local encoded = mime.b64("test string")
local decoded = mime.unb64(encoded)

-- connect to a webserver
sock:settimeout(5)
sock:connect("www.fbacreator.com", 80)
sock:send("GET /downloads/misc/tutorial_file.php HTTP/1.0\r\n")
sock:send("Host: www.fbacreator.com\r\n\r\n")

local host,port = sock:getpeername()

function onmainloop()
        clear(0,0,0)
        
        print(10,10,"YOU MUST BE CONNECTED TO INTERNET IN ORDER TO TEST THIS SAMPLE",0,0,255)
        print(10,30,"CONNECTED TO " .. host .. " ON PORT " .. port,0,255,0)
        print(10,50,"STRING FETCHED: " .. finalStr,255,0,0)
        print(10,100,"DEMO B64 ENCODED STRING: " .. encoded,255,255,0)
        print(10,120,"DEMO B64 DECODED STRING: " .. decoded,255,255,0)

        data,err = sock:receive()
        if data ~= nil then
                if data == "" then
                        waitheader = waitheader + 1
                elseif waitheader == 2 then
                        finalStr=data
                end
        end
end

function onstylusdown(x,y)
        quit()
end

function onquit()
        sock:close()
end
