B4J Question [SERVER] GET

jesuslizonsoluciones

Member
Licensed User
Longtime User
Hi all


I have a question which is the following:


I am using Jserver in a server application; everything works correctly for me until I make a GET request from outside; it closes without having finished the process.


This happens to me especially when I am waiting for some internal process to finish with the waitford command


Is there an example where I can look at the GET process ????


I use jserver and the GET requests are made from the POSTMAN program


Greetings and thank you
 

Magma

Expert
Licensed User
Longtime User
will be better - if posting a sample of code...

but do you mean something like this:

B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)

    
    resp.ContentType = "text/html"

    Dim example As String = req.GetParameter("a")
    ...

get of client at a browser: http://www.yourdomain.ext/test?a=TEST

So example string when the client browser --> browse the address http://www.yourdomain.ext/test?a=TEST --> will have the value "TEST"...
 
Upvote 0

Magma

Expert
Licensed User
Longtime User
Mi problema esque el Get se realiza externamente GET https://127.0.0.1:8888/scan.

Me salta sin problema el evento Handle y a continuacion me conecto con un servidor via socket y en el momento que salta el evento

Sub Client_connected(Successful As Boolean)

Log ("conectado")

End Sub

envia al que realiza la peticion GET el status 200 OK, y aun no ha terminado el proceso

can't understand your language...

So... in Main add:
B4X:
...
    srvr.AddHandler("/scan", "scan",  False)
...

create class server handle module with name: "scan"

B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)

  
    resp.ContentType = "text/html"

    Dim example As String = req.GetParameter("a")
    ...

get of client at a browser: http://www.yourdomain.ext/scan?a=TEST

So the "example" string when the client browser --> browse the address http://www.yourdomain.ext/scan?a=TEST --> will have the value "TEST"...
 
Last edited:
Upvote 0

jesuslizonsoluciones

Member
Licensed User
Longtime User
Upvote 0

jesuslizonsoluciones

Member
Licensed User
Longtime User
Hi there


I send you the code where you can see the problem I have. I have never used Jserver with Jnetwork


a greeting




B4X:
  Sub Handle(req As ServletRequest, resp As ServletResponse)
    'Try
    
        mreq = req
        mresp = resp
        
        
        
        Log("scan")
        
        Log(req.ContentType.SubString(0))
        
        If req.ContentType.StartsWith("application/json") Then
        
            Dim jo As JavaObject = req
            Dim collections As JavaObject
            collections.InitializeStatic("java.util.Collections")
            Dim headers As List = collections.RunMethod("list", Array(jo.RunMethodJO("getHeaderNames", Null)))
            For Each h As String In headers
                Log(h & ": " & req.GetHeader(h))
            Next
        
        
            Try
            
                Dim data() As Byte = Bit.InputStreamToBytes(req.InputStream)
            
                Dim text As String = BytesToString(data, 0, data.Length, "UTF8")

            '    resp.Write(text)
                
                
                Log("texto " & text)
                
                
                Dim parser As JSONParser
                parser.Initialize(text)
                Root1  = parser.NextObject
                Origin = Root1.Get("Origin")
                HostVendor = Root1.Get("Host")
                
                Log ("origen " & Origin)
                Log("Host " & HostVendor)
                
                '****************************************llamar al programa de socket para enviar
          
            
                
                
              [COLOR=rgb(226, 80, 65)] ConnectToServer("192.168.1.100",6680)  '   socket server [/COLOR]
              
                Wait For Client_connected (Successful As Boolean)
              
                [COLOR=rgb(226, 80, 65)]If Successful Then      '  
[/COLOR]
                        At this moment, it has already sent the response 200 OK to the GET request.

                    
                    Log("conectado")
                    
                End If
                
            Catch

                resp.SendError(500, LastException)
                Log("Error")

            End Try
        
        
        
        End If
        
        
        
        
        
    'Log("hola")   
        
        
        
        
        
    
End Sub
 
Upvote 0

Magma

Expert
Licensed User
Longtime User
In a server... you never wait someone to connect... server is there always... the handle works anytime.... the user (from client device)...

The Wait For Client_connected seems that not needed... if i can understand.. what you want...

At the Main...

You set the port
B4X:
Sub Process_Globals

    Public srvr As Server
end sub


Sub AppStart (Form1 As Form, Args() As String)

    srvr.Initialize("srvr")
    srvr.Port = 8888
    srvr.AddHandler("/scan", "scan",  False)

    srvr.Start
end sub

....And you must create the server class module "scan" (as you said already created)


check the example i ve wrotten to you
So when the client (device) call the address of your server at port you set... /scan?a=test

B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)

  
    resp.ContentType = "text/html"

    Dim example As String = req.GetParameter("a")
log("example")

Any time the server will catch get requests... no need to wait...

Is that you want... ?
 
Upvote 0

jesuslizonsoluciones

Member
Licensed User
Longtime User
Not quite


I send you the file with the project, so you can see exactly what happens to me ... It seems to be a problem when a process is waiting, it cuts the link


I hope you can help me as it is urgent


try it in web browser like http://127.0.0.1:8888/scan


Thank you very much, I wait for news
 

Attachments

  • HelloWorld.zip
    80.6 KB · Views: 134
Upvote 0

Magma

Expert
Licensed User
Longtime User
@jesuslizonsoluciones just downloaded... and test... well from server side all now seems ok...

i just replaced cmd.exe with msinfo32.exe - to see if works...

B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)
   
   
    resp.Write("let' try to run msinfo32 at server... for 2secs...")
   
               
    Sh.Initialize("sh","msinfo32.exe", Null) 
    Sh.WorkingDirectory = "C:\"
    Sh.Run(2000) 'works - run ok for 2 sec...
   
    wait For (Sh) sh_ProcessCompleted (Success As Boolean, ExitCode As Int, StdOut As String, StdErr As String)
    'hmmm that is not working...  for some reason i can't understand --- but never taking logs..

  
   
End Sub
Sub sh_ProcessCompleted (Success As Boolean, ExitCode As Int, StdOut As String, StdErr As String)
    If Success And ExitCode = 0 Then
        Log("Success")  'never take logs...
        Log(StdOut)
    Else
        Log("Error: " & StdErr)
    End If
   
End Sub

But as i am thinking the sh solution will have many problems... the commands are working

example of other solution:
If you wanna just run for example a "dir" command or anything that will be at cmd line and will exit at some seconds - it is better to output at a file and then read to get the whole results...

the command for "dir" getting files will be "dir c:\somefolder >c:\output.txt" ---- but the problem will be "if" in the same time some other user (client) ask from his browser the same thing-same time so the output.txt must be output[num].txt ----> raising number ...

After that you can read the file anytime you want to get results or errors....

For the part of taking exitcodes... why not working... i don't know... never used it like this - but is like the solution i gave you - because i want more than an exitcode...
+ the best solution for me with sh... is:
B4X:
Sh.RunSynchronous(-1)
 
Upvote 0

jesuslizonsoluciones

Member
Licensed User
Longtime User
Thank you


this problem happens with all wait for instructions


I have been able to solve it by reading this link https://www.b4x.com/android/forum/threads/wait-for-on-server-handle.120372/


I give you the code that works correctly


thank you very much

B4X:
Sub Handle(req As ServletRequest, Resp As ServletResponse)

    Ejecutar(Resp)

    StartMessageLoop   
    
    Resp.Write("Second")
    
    
End Sub


Sub Ejecutar( Respuesta As ServletResponse)
    
    Sh.Initialize("sh","cmd",Null)
    Sh.WorkingDirectory = "C:\"
    Sh.Run(2000)

    Wait For sh_ProcessCompleted (Success As Boolean, ExitCode As Int, StdOut As String, StdErr As String)
    
    Respuesta.Write("perfecto")
    
    StopMessageLoop
    
End Sub
 
Upvote 0
Top