B4J Tutorial [Server] Building web servers with B4J

Status
Not open for further replies.
Edit: Web Apps tutorial: http://www.b4x.com/android/forum/threads/webapp-web-apps-overview.39811/

The server implementation is based on a popular and powerful Java server library named Jetty (license)
The database connection pooling implementation is based on c3p0 (license).


B4J Server features:
  • High performance web server
  • Automatic handling of static files
  • Simple to develop custom "handlers"
  • Support for GET, POST, DELETE and PUT requests
  • Support for multipart requests (file uploads)
  • Standard logging
  • Each handler can either be multi-threaded or single-threaded
  • Simple and powerful database connections pooling
  • Server can run on Windows, Mac and Linux (including board computers such as Raspberry Pi)

Possible usages
  • Internal or external web sites
  • Backend solutions (with or without UI) that can optionally connect to any type of database


If you never worked with web servers then it is recommended to start with a HTTP tutorial such as this one: http://net.tutsplus.com/tutorials/t...rotocol-every-web-developer-must-know-part-1/

I also recommend you to use a proper browser with debugging plugin such as FireFox + FireBug. The ability to inspect the requests and responses is very useful.

How it works

A server program is a non-UI program.
In the Main module you should create a Server object, configure it, start it and call StartMessageLoop:
B4X:
Sub Process_Globals
   Private srvr As Server
End Sub

Sub AppStart (Args() As String)
   srvr.Initialize("srvr")
   srvr.Port = 8888
   srvr.StaticFilesFolder = File.Combine(File.DirApp, "www")
   srvr.AddHandler("/hello", "HelloPage", False)
   srvr.AddHandler("/FormExampleHelper", "FormExampleHelper", False)
   srvr.AddHandler("/FileUpload", "FileUpload", False)
   srvr.Start
   StartMessageLoop
End Sub

As you can see in the above code, the port is set to 8888.
StaticFilesFolder sets the folder (and subfolders) that will be used to serve static files. Any file that is not generated by your code is a static file (html, js, css, images, etc.).
Files outside of this folder cannot be accessed. This is important for security reasons.
Note that if the url points to a folder then the index.html file in that folder will be served (if it exists).

Handlers

A handler is a B4J class that is mapped to a URL. A handler class is responsible for getting the request and providing the response.

Each request is handled by a new instance of the handler class. A handler class should have an empty Initialize and a Handle sub with the following signature:
B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)

You should read the data from the ServletRequest and write the response to the ServletResponse.

For example:
B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)
resp.Write("Hello World!")
End Sub

The attached example includes three handlers:
HelloPage - A simple handler that creates the following page:

SS-2014-01-27_16.49.30.png

Note that this page was served from a Raspberry Pi board :)

FormExampleHelper - This handler receives a submitted form and prints the form's fields. It is used by two html pages. A simple form page and a page that uses Ajax (with JQuery) to send the form.

FileUpload - This handler receives a multipart form with a file and other fields. It logs the fields and the file size.

Threading

When you add a handler you need to specify whether you want it to be a single threaded handler or a multithreaded handler. By default you should use multithreaded handlers (third parameter should be false).

A multithreaded handler means that your handler code will be run by a thread from the server threads pool. Multiple instances of the same handler and other handlers can be executed in the same time. As long as you don't access any global variable out of the current handler instance you should be safe.

A single threaded handler will always be executed by the main thread. This means that if there are multiple requests they will be queued and executed one by one. Single threaded handlers can be useful in many cases. Some examples:
- A handler that accesses a SQLite database, which is less suitable for concurrent connections. See this tutorial for concurrent access to SQLite: https://www.b4x.com/android/forum/t...ent-access-to-sqlite-databases.39904/#content
- A handler that writes to a specific file.
- A handler that sends a job to the printer

Note that when you run your code in Debug mode the handlers will always run in the main thread.

Datebase Connections Pooling

Many web servers are based on databases. Databases, such as MySQL and others, can properly handle concurrent queries and transactions. The ConnectionPool object handles a pool of database connections. You can then get a connection (SQL object) from the pool, work with it and close it, which will actually return it to the pool.

The pool is responsible for maintaining the connections.
An alternative for a connections pool is a process global SQL variable. However for it to work properly all the handlers should be single threaded handlers.

As explained in the SQL tutorial you should use #AdditionalJar attribute to add a reference to the JDBC jar. You should then make a public process global pool variable and use it from the handler.


To try this example, run it from B4J and point the browser to 127.0.0.1:8888
This will load the index.html file that is available in the www folder.

Examples & Tutorials:

Online examples: https://www.b4x.com:51041
Other server tutorials: http://www.b4x.com/android/forum/pages/results/?query=[server]&page=1&prefix=0
 

Attachments

  • ServerHelloWorld.zip
    79.8 KB · Views: 6,645
Last edited:

wl

Well-Known Member
Licensed User
Longtime User
Hi Erel,

What I meant was:

You run the webserver on a machine that is hosting websites for www.domain1.com and www.domain2.com (both resolving to the same IP of course = IP on which the webserver is running). The staticfilesfolder for requests to www.domain2.com should be a folder \domain1 and for requests to www.domain2.com should be folder \domain2.

Thx
 

wl

Well-Known Member
Licensed User
Longtime User
thanks Erel, but that's a bummer. Only possibility would be to put an nginx (or similar) in front of it then...
 

Roberto P.

Well-Known Member
Licensed User
Longtime User
would be very helpful for a complete sample database connection for data exchange with dektop application or mobile ...
thanks in advance
 

wl

Well-Known Member
Licensed User
Longtime User
Hi,

As the cookies have not been implemented yet: wouldn't it just be possible to set a cookie by writing/reading the correct HTTP header (Set-cookie:) ?

Tx
 

rwblinn

Well-Known Member
Licensed User
Longtime User
Great work - based upon B4J v1.8, I have build a simple ToDoServer. See readme.txt and the code for how it works.
So far this is based upon accessing from the client via a webbrowser.

b4jhowtowebserver.png


Download the code here:http://www.rwblinn.de/b4j/b4jhowto/examples/b4jhowtowebserver.zip

Next is to develop a B4A dedicated client to access this B4J webserver with add, update and delete functionality - or a volunteer can do ;).
 

little3399

Active Member
Licensed User
Longtime User
Hi,Erel

Does the jar file can be put it on the webserver ? such as tomcat ? Tks!
 

barx

Well-Known Member
Licensed User
Longtime User
What exactly is required to run these server apps. i.e. can they be run on Internet based servers? If, so, what is required. Can they run on shared plans (i'm doubting it), vps, etc??

It looks very, very interesting and I have literally just started trying to learn Symfony2. This B4J solutions looks similar in structure (MVC).

Thanks
 

chrjak

Active Member
Licensed User
Longtime User
This is my error when i tick the JServer Library:

Parsing code. 0.01
Compiling code. 0.02
Compiling generated Java code. Error
Cannot find: C:\Program Files (x86)\Anywhere Software\B4J\libraries\jetty_b4j.jar

:(

Edit: News: I downloaded the latest Version of b4j and installed it. Now there is no error.
But the Designer in the Menu Bar is gray and i have a question:

How do you get these numbers? (192.168....:8888)
Edit 2: In the Log is 0.0.0.0:8888 - but i can't connect to it
 
Last edited:

chrjak

Active Member
Licensed User
Longtime User
Thank you. i will return the the old threat again. see you there
 

cstangor

Member
Licensed User
Longtime User
I don't understand which files need to be uploaded to my server for this to function.

I have the files from the www (staticfiles) folder but that doesn't seem to be enough.

Thanks in advance
 
Status
Not open for further replies.
Top