B4J Tutorial Making an extensible Web Server with jServer

I use jServer/Server extensively. One thing I've struggled with is the fact that I have several huge B4J projects which keep on growing and each one requires its own port. I've longed to be able to split my web server into separate projects that I can update handlers in isolation.

I was reading @keirS post the other day and an idea struck. If we can separate server handlers into separate B4J library projects (ie jars) then we could possibly load these handlers at run time from a single web server project.

The first step was to create a library to load a jar at run time. See jarLoader;

https://www.b4x.com/android/forum/threads/jarloader.81393/#post-515871

Next was to prove I could create a server handler class library and load this at run time.

Luckily Erels jServer AddHandler method actually accepts a fully qualified class name meaning you can actually create a handler for a class that is not part of your project.

So putting all of the pieces together we can now (at runtime) create handlers for jServer using external jar files.

Here is a small snippet to demonstrate.

B4X:
Sub AppStart (Args() As String)   
    Dim j As jarLoader
    j.loadJAR(File.DirApp & "\handlerclass.jar")
       
    srvr.Initialize("")
    srvr.Port = 80
   
    srvr.AddHandler("/test","nz.ope.handlerclass.test",True)

    srvr.LogsRetainDays = 7
    srvr.LogWaitingMessages = False

    srvr.Start
   
    StartMessageLoop
End Sub

The full project and handler class library are attached.

If it all works you should see a handler response at http://localhost:80/test

NOTE The handlerclass must be compiled as a library from B4J.
 

Attachments

  • HandlerServer.zip
    27.3 KB · Views: 354

tchart

Well-Known Member
Licensed User
Longtime User
jUtilities is a Java library I maintain to assist my development. Its not essential for this project. I simply use it to open the server page in a browser.
 

Attachments

  • jUtilities.zip
    4.3 KB · Views: 352

keirS

Well-Known Member
Licensed User
Longtime User
Glad someone spotted it's broader applications :) In theory it's possible to unload a JAR as well. This is rather more complex as it requires a custom class loader / unloader. It's something I will be investigating though as it means you can dynamically update a server without needing to stop and restart it.
 
Top