Android Question Http Server with HttpJob is not sync?

susu

Well-Known Member
Licensed User
Longtime User
Hi,

Base on Erel's example of Http Server, I wrote this code to get public IP and export to webpage:

B4X:
Sub Server_HandleRequest (Request As ServletRequest, Response As ServletResponse)   
    Try
        Select True
            Case Request.RequestURI = "/"
                Dim Job As HttpJob
                Job.Initialize("Job1", Me)
                Job.Download("http://api.ipify.org/")               
                HandleMainPage (Response)
            Case Else
                SetContentType(Request.RequestURI, Response)
                Response.SendFile(File.DirAssets, DecodePath(Request.RequestURI.SubString(1)))
        End Select
    Catch
        Response.Status = 500
        Response.SendString("Error serving request: " & LastException)
    End Try
End Sub

Sub JobDone (Job As HttpJob)
    If Job.Success Then
        Select Job.JobName
            Case "Job1"
                PrintYourIP(Job.GetString)
                count = count + 1
                Log("Count " &count)
                Log(Job.GetString)
        End Select
    Else  'Failed
        Select Job.JobName
            Case "Job1"
                Log("Failed to get IP")
        End Select
    End If
    Job.Release
End Sub

Sub PrintYourIP(s As String)
    YourIP = " Hey, Your IP is "&s
End Sub

Sub HandleMainPage (Response As ServletResponse)
    Dim MainPage As String = GetTemplate("main_template.html") 'load the template from the assets folder
    MainPage = MainPage.Replace("$TIME$", DateTime.Time(DateTime.Now))
    Dim information As StringBuilder
    information.Initialize
    information.Append(count).Append(YourIP).Append("<br/>")
    MainPage = MainPage.Replace("$OTHERINFORMATION$", information)
    MainPage = MainPage.Replace("$GREETING$", greeting)
    Response.SetContentType("text/html")
    Response.SendString(MainPage)
End Sub

In Logcat I see it work correctly:
Count 1
27.3.2XX.XXX
But in webpage it not show anything until I refresh it. Then in Logcat it likes:
Count 2
27.3.2XX.XXX
and in webpage it shows: 1 Hey, Your IP is 27.3.2XX.XXX
How can I make the webpage always show right value? Thank you.

Ps: Please find attachment for sample code.
 

Attachments

  • httpserver-getip.zip
    57.8 KB · Views: 295

DonManfred

Expert
Licensed User
Longtime User
sure it is sync. But you need to answer in the Server_HandleRequest event directly.
But you are leaving the sub to do a download (in this case to get the ip).

You can use a time for ex. in the server to check the ip every x minutes and then store the answer so you can use the stored value in the Server_HandleRequest event and send it directly in the response object.
 
Upvote 0

susu

Well-Known Member
Licensed User
Longtime User
Thanks Don. How can I handle Server Request after HttpJob finish?
 
Upvote 0
Top