B4J Tutorial [Server] Upload files from your B4A app to your B4J server over the internet

Status
Not open for further replies.
This example shows how to make your B4J server application accessible over the internet.

The implemented server is a simple file server that allows you to upload files from your B4A application to the server over the internet.

The following steps are required in order to make your server accessible over the internet:
  1. As the router (or computer) external IP address changes from time to time we need to use a service that maps a known address to our dynamic address. In this case I used a free service named DuckDNS. You should register with them and choose a unique domain for your server.
    They will also provide you with a token. In the Main module we use a timer to call their service (with this token) every 10 minutes. This updates the IP address if needed.
  2. Router setup
    • Port forwarding - Configure the router to forward all incoming requests on the given port to your computer address.
    • Static IP - On some routers port forwarding will only work with a specific local IP address. The solution is to configure the router to always provide your computer with the same address.
    • Search Google for instructions specific to your router.
  3. Firewall - You need to allow incoming connections on the specific port.
Tips:
- There are several points of failures in this configuration. In order to debug it, run the server and call the test handler. Start with calling it from the computer browser (127.0.0.1:54021/test). If there is an error then the server is not running properly.
Now try to call it with duckdns: yourdomain.duckdns.org:54021/test
If it works then the configuration is probably fine. You just need to test it from outside the local network.
If it doesn't work then find your external ip address and try to call it. If it doesn't work with the external ip address then your router is not configured correctly or the firewall is blocking the incoming connection.

- Don't worry. Eventually you will get it working :)

Now for the actual file server. The handler is quite simple. It supports two types of messages: text messages and files. The handler reads the data directly from the request input stream. The type parameter (from the query string) tells it whether to treat the data as a text message or as a file that needs to be saved.

One important point is that we need to call req.InputStream before calling req.GetParameter. Otherwise the complete stream will be internally read as the server looks for the parameter in the request body. This will not happen if we first call req.InputStream.

The Android application is quite simple. It just uses HttpUtils2 to send the file or text message.

upload_2014-1-28_13-9-44.png


In order to run it you need to update the link variable based on your domain name.

This tutorial opens the door to many interesting solutions. You can easily turn any PC into a backend server for your Android applications.
 

Attachments

  • FileClient-B4A.zip
    7.5 KB · Views: 4,158
  • FileServer-B4J.zip
    4.3 KB · Views: 4,408

YIM bunchhat

Active Member
Licensed User
hello,...I tested but it doesn't work. when I start server on PC I got : Update DuckDNS: OK, when I test with your example I got Update DuckDNS: KO. When I send string form phone I got error. I already configure router port forward and open firewall. what's wrong? I use router TP-link
 

YIM bunchhat

Active Member
Licensed User
Hello I still cannot. I follow you by ip address I got as picture below. I configure my router like this is it correct? Untitled.png

There are several points of failures in this configuration. In order to debug it, run the server and call the test handler. Start with calling it from the computer browser (127.0.0.1:54021/test). If there is an error then the server is not running properly.]

On this point what you means and how to do it? call handle we need to add code to Main or not? Sorry I am new with coding
 

Attachments

  • Untitled.jpg
    Untitled.jpg
    48.3 KB · Views: 305
Last edited:

YIM bunchhat

Active Member
Licensed User
Here is your sample I modify it only on domain and token is it correct?
B4X:
Non-UI application (console application)
#Region  Project Attributes
    #CommandLineArgs:
    #MergeLibraries: False
#End Region

Sub Process_Globals
    Private domain As String = "chhat"
    Private token As String = "07d52e48-f68a-4b47-85e8-1d7b7834106c"
    Private updateIp As Timer
    Private srvr As Server
    Public filesFolder As String = "uploaded"
End Sub

Sub AppStart (Args() As String)
    updateIp.Initialize("updateIp", 60 * 1000) '10 minutes
    updateIp.Enabled = True
    UpdateIp_Tick
    srvr.Initialize("srvr")
    srvr.Port = 54021
    File.MakeDir(File.DirApp, filesFolder)
    srvr.AddHandler("/upload", "Upload", False)
    srvr.AddHandler("/test", "Test", False)
    srvr.Start
    Log("Server started")
    StartMessageLoop
End Sub

Sub UpdateIp_Tick
    Dim j As HttpJob
    j.Initialize("j", Me)
    j.Download2("http://www.duckdns.org/update", Array As String("domains", domain, "token", token, _
        "ip", ""))
End Sub

Sub JobDone (j As HttpJob)
    If j.Success = True Then
        Log("Update DuckDNS: " & j.GetString)
    Else
        Log("Error updating Duck DNS: " & j.ErrorMessage)
    End If
    j.Release
End Sub
 

somed3v3loper

Well-Known Member
Licensed User
It is actually simpler than I wrote. The server handles "static" files automatically. You just need to put the files under the static files folder and they will be accessible. You do not need a custom handler for that.

Can server download file from internet and send it to client ?
I am thinking of making a small proxy .
What I tried is getting url from client in a handler class then download the file (http job) when job finishes I use File.Copy2(job.GetInputStream , ...) to write to resp.OutputStream .
But as you can see Sub Handle(req As ServletRequest, resp As ServletResponse) should have finished at that time
 

nonno

Active Member
Licensed User
Erel devo inviare un file txt di piccola dimensione tramite wifi da cellulare al pc
non riesco potresti darmi dei consigli( non sono programmatore conosco abbastanza il linguaggio VB6)
Grazie mille
 

HAH

Well-Known Member
Licensed User
Hi
We are connected to internet through ADSL from ourl local ISP.
Our local ISP NAT-ing us, for example:
If i connected to the internet; my adsl modem got this ip 10.33.19.74 but if i checked my ip in google i got this different ip 109.200.183.132
From internet outside of my adsl i can't connected to our local server by following the above roles !

Any suggestion please ...
 

HAH

Well-Known Member
Licensed User
This is called carrier grade NAT (CGN). You will not be able to connect to your computer from outside unless your ISP provides you a real and unique IP address.

You should contact your ISP.
Our ISP doesn't respond to us!
Can we work around it?
when i using teamviewer, it work fine, Is their any solution exists like teamviewer ?
 
Status
Not open for further replies.
Top