B4J Library [B4X] xHttpServer (Http Server + jQuery)

It is a personal project of mine that I started as a hobby on B4i and it has become an interesting project, so that I have modified it to be multiplatform.

It is an http server, which allows a browser to navigate on html pages stored on the device. In addition, dynamic pages can also be created. Read the parameters of the GET and POST commands and read and write the COOKIES in the browser.
It also implements the WebSocket, starting from an example published in this forum by @Erel for the jServer library. I also made the jQueryElement class to interface with the JavaScript elements of the Browser page.
(You can get the source of the QueryElement class at this Post)

Obviously it is not at the level of existing and established servers, but it is a project that I want to share and that I think can be useful since it is cross-platform. The examples are in post 2

It is entirely written in B4X.
It may have some bugs
It does not support SSL / TLS. I didn't understand how it works.


aHttpServer

Author:
Star-Dust
Version: 0.75
  • QueryElement
    • Events:
      • change (Resp As ServletResponse, Params As Map) ' QueryElement Event Click
      • click (Resp As ServletResponse, Params As Map) ' QueryElement Event Click
      • dblclick (Resp As ServletResponse, Params As Map) ' QueryElement Event Click
      • focus (Resp As ServletResponse, Params As Map) ' QueryElement Event Click
      • focusin (Resp As ServletResponse, Params As Map) ' QueryElement Event Click
      • focusout (Resp As ServletResponse, Params As Map) ' QueryElement Event Click
      • keyup (Resp As ServletResponse, Params As Map) ' QueryElement Event Click
      • mousedown (Resp As ServletResponse, Params As Map) ' QueryElement Event Click
      • mouseenter (Resp As ServletResponse, Params As Map) ' QueryElement Event Click
      • mouseleave (Resp As ServletResponse, Params As Map) ' QueryElement Event Click
      • mousemove (Resp As ServletResponse, Params As Map) ' QueryElement Event Click
      • mouseup (Resp As ServletResponse, Params As Map) ' QueryElement Event Click
    • Fields:
      • Event_change As String
      • Event_click As String
      • Event_dblclick As String
      • Event_focus As String
      • Event_focusin As String
      • Event_focusout As String
      • Event_keyup As String
      • Event_mousedown As String
      • Event_mouseenter As String
      • Event_mouseleave As String
      • Event_mousemove As String
      • Event_mouseup As String
      • NoEvent As Map()
    • Functions:
      • Class_Globals As String
      • CreateEvent (ObjectName As String, Event As String, OtherEvent As Map()) As Map()
      • EscapeHtml (Raw As String) As String
      • Eval (Script As String, Params As List) As String
      • EvalWithResult (Script As String, Params As List) As String
      • GetPropriety (Property As String, Value As List) As String
      • GetVal (ID As String, ValueList As List) As String
      • Initialize (Response As ServletResponse) As String
        Initializes the object. You can add parameters to this method if needed.
      • IsInitialized As Boolean
        Verifica se l'oggetto sia stato inizializzato.
      • RunFunction (function As String, ID As String, Params As List) As String
        Param = list or array: array as Map or String (array as Object is wrong)
      • RunFunctionWithResult (function As String, ID As String, Params As List) As String
      • RunMethod (Method As String, ID As String, Params As List) As String
        Param = list or array: array as Object is wrong - array as Map is correct
      • RunMethodWithResult (Method As String, ID As String, Params As List) As String
        Param = list or array: array as Object is wrong - array as Map is correct
      • SelectElement (ID As String) As String
      • SetCommand (etype As String, Method As String, property As String, ID As String, Params As List, Arg As List) As String
      • SetCSS (id As String, Params As List) As String
      • SetDialog (id As String, Params As List) As String
        Public Sub GetWidth As Object
        End Sub
      • SetHtml (id As String, Params As List) As String

        Public Sub SetHeight (Value As String)
        End Sub
      • SetPropriety (Property As String, Value As List) As String
      • SetText (ID As String, TextList As List) As String
      • SetVal (ID As String, ValueList As List) As String
    • Properties:
      • AutomaticEvents
  • ServletRequest
    • Fields:
      • CharacterEncoding As String
      • ConnectionAlive As Boolean
      • ContentLength As Long
      • ContentType As String
      • ID As String
      • LogActive As Boolean
      • LogFirstRefuse As Boolean
      • MultipartFilename As Map
      • RequestCookies As Map
      • RequestHeader As Map
      • RequestParameter As Map
      • RequestPostDataRow As List
      • Timeout As Long
    • Functions:
      • ArrayInsert (DataSource As Byte(), Index As Int, DataInsert As Byte()) As Byte()
      • ArrayRemove (Data As Byte(), Start As Int, Last As Int) As Byte()
      • Class_Globals As String
      • Close As String
      • Connected As Boolean
      • GetHeader (Name As String) As String
      • GetHeadersName As List
        can be used to iterate over Header
        Example
        <code>
        For Each Name As String In ServletRequest.GetHeadersName
        Log("Value = " & ServletRequest.GetHeader(Name))
        Next</code>
      • GetInputStream As InputStream
      • GetMethod As String
      • GetRequestHOST As String
      • GetRequestURI As String
      • GetWebSocketCompressDeflateAccept As Boolean
      • GetWebSocketCompressGzipAccept As Boolean
      • GetWebSocketMapData As Map
      • GetWebSocketStringData As String
      • Initialize (CallBack As Object, EventName As String, Sck As Socket) As String
        Initializes the object. You can add parameters to this method if needed.
      • IsInitialized As Boolean
        Verifica se l'oggetto sia stato inizializzato.
      • ParameterMap As Map
      • RemoteAddress As String
      • RemotePort As Int
      • SubArray2 (Data As Byte(), Start As Int, Last As Int) As Byte()
  • ServletResponse
    • Fields:
      • CharacterEncoding As String
      • ContentLenght As Int
      • ContentType As String
      • Status As Int
    • Functions:
      • Class_Globals As String
      • Close As String
      • Connected As Boolean
      • Initialize (Req As ServletRequest, ast As AsyncStreams, Sck As Socket) As String
        Initializes the object. You can add parameters to this method if needed.
      • IsInitialized As Boolean
        Verifica se l'oggetto sia stato inizializzato.
      • ResetCookies As String
      • SendFile (Dir As String, fileName As String) As String
        don't use DirAssets
      • SendFile2 (Dir As String, fileName As String, Content_Type As String) As String
      • SendNotFound (filenameNotFound As String) As String
      • SendRaw (Data As Byte()) As String
      • SendRedirect (Address As String) As String
      • SendString (Text As String) As String
        sending text with Header
      • SendWebSocketBinary (Data As Byte(), Masked As Boolean) As String
      • SendWebSocketClose As String
      • SendWebSocketPing As String
      • SendWebSocketPong As String
      • SendWebSocketString (Text As String, Masked As Boolean, Compressed As String) As String
        Cmpressed as Deflate=zlib, gzip, none - (set always none)
      • SetCookies (Name As String, Value As String) As String
        Set Cokies values on Browser
      • SetHeader (Name As String, Value As String) As String
      • Write (Text As String) As String
        Sending text without header to dynamically send more text after the SendString
    • Properties:
      • OutputStream As OutputStream [read only]
      • Query As QueryElement [read only]
  • httpServer
    • Events:
      • Handle (req As ServletRequest, resp As ServletResponse)
      • HandleWebSocket (req As ServletRequest, resp As ServletResponse)
      • NewConection (req As ServletRequest)
      • SwitchToWebSocket (req As ServletRequest, resp As ServletResponse)
      • UploadedFile (req As ServletRequest, resp As ServletResponse)
      • WebSocketClose (CloseCode As Int, CloseMessage As String)
    • Fields:
      • DigestAuthentication As Boolean
      • DigestPath As String
      • htdigest As List
      • IgnoreNC As Boolean
      • realm As String
      • Timeout As Int
    • Functions:
      • Class_Globals As String
      • GetMyIP As String
      • GetMyWifiIp As String
      • Initialize (CallBack As Object, EventName As String) As String
        Initializes the object. You can add parameters to this method if needed.
      • IsInitialized As Boolean
        Verifica se l'oggetto sia stato inizializzato.
      • Start (Port As Int)
        eg. Start(51051)
      • Stop As String
    • Properties:
      • TempPath As String [read only]
 

Attachments

  • aHttpServer 0.75.zip
    35.1 KB · Views: 78
  • jHttpServer 0.75.zip
    34.8 KB · Views: 61
  • iHttpServer 0.75.zip
    423 KB · Views: 59
Last edited:

OliverA

Expert
Licensed User
Maybe it's just me, but I could not extract the
iHttpServer 0.73.zip
file using Windows 10's build in unzip function. Had to use 7Zip. I do not encounter the same issue with the the B4J or B4A library extraction.
2021-04-13.png
 

Star-Dust

Expert
Licensed User
You should learn how to search the forum

 

Darsiar

Member
As students, we wrote something similar. But this is very good! Please give your library code! Maybe we can add something useful.
Thank you
 

Darsiar

Member
1) We cannot write to you privately, therefore, in our version, browsers for some reason do not give private letter buttons. Or have we been foolishly looking for this button for a letter for a long time and do not find it?

2)
We cannot send donations, as we are a group of schoolchildren and students from Belarus. Here the average worker's income is less than $ 450 per month, and the student's scholarship is about $ 100 per month.
We are sorry. We can only participate and help the project.

3) We tried it on the phone, with a SIM card and forwarding to port 80:

B4X:
dim sur As SuCommand
sur.SuCommand ("iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8088")

It works really well!
We want to slightly modify your library.
There are interesting ideas on what else to add from the functions.
In particular, it seems to us (no offense) that the idea of archiving a package of start web pages into an internal folder is not quite the right thing to do.
We would suggest using a virtual memory card (map), and place it on the external cd area.
It is also useful to add the function of reading cookies.
As far as certificates are concerned, this can also be dealt with.

Let's collaborate.
Please send the source code for your library.
We will coordinate all improvements with you.

Sincerely.
 

Star-Dust

Expert
Licensed User
As students, we wrote something similar. But this is very good! Please give your library code! Maybe we can add something useful.
Thank you
Dear Students, if you have written something similar it would be nice if you share it with us in a new Topic. If you think mine is very good I might be adding something useful to your code

1) We cannot write to you privately, therefore, in our version, browsers for some reason do not give private letter buttons. Or have we been foolishly looking for this button for a letter for a long time and do not find it?

2)
We cannot send donations, as we are a group of schoolchildren and students from Belarus. Here the average worker's income is less than $ 450 per month, and the student's scholarship is about $ 100 per month.
We are sorry. We can only participate and help the project.

3) We tried it on the phone, with a SIM card and forwarding to port 80:
I see that in Belarus you have the same salaries as in Sicily, this unites us.
For this solidarity reason, I have established that no donation is required to use my library.

B4X:
dim sur As SuCommand
sur.SuCommand ("iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8088")

It works really well!

We want to slightly modify your library.
There are interesting ideas on what else to add from the functions.
In particular, it seems to us (no offense) that the idea of archiving a package of start web pages into an internal folder is not quite the right thing to do.
We would suggest using a virtual memory card (map), and place it on the external cd area.
It is also useful to add the function of reading cookies.
As far as certificates are concerned, this can also be dealt with.

Let's collaborate.
Please send the source code for your library.
We will coordinate all improvements with you.

Sincerely.
There is no offense in the remarks made in a polite manner.

1) Actually the web pages are stored in internal folders just for the convenience of the example. I used B4XPages and had to use a standard that was good on 3 platforms (Android, iOs, Desktop). As you well know, on iOs you cannot go outside the application's internal folders. In android it is possible to do this with more and more complex methods as the SDK version grows.
But it is clear that on a PC (Windows / Mac / Linux) it would not be useful to store pages in internal folders.
This is something you can change without having to modify the library

2) There is already a method to read and set cookies (see ServletRequest. RequestCookies and ServletResponse. SetCookies ) , so it does not need updates in this sense. Looking carefully at the properties of the library you will find how.

I am very pleased that you are interested in protocols, it is a subject that has fascinated me since I was a boy.
I mainly studied the protocols of many Chats and instant messaging, available at the time, and I have developed alternative VB6 clients with greater potential. To be clear a kind of Trillian (for those who know what I'm talking about). Keep it up.
 
Last edited:

Darsiar

Member
Thank you very much for your kind answer!
Unfortunately. installing and reading cookies in your library doesn't work (at least it didn't work for us).
If you are interested, we can send the source code of a large web project for the artificial intelligence language with a built-in website generator (cms), and a built-in associative graph knowledge base. It has the capabilities of Prolog, the syntax is simpler than that of Basic and the ability to process texts in natural language (Russian, English), as well as complex associative conclusions ...
The language is called Friend, and from the very beginning it is a web server with a built-in editor and admin panel.
We can send the source code, - the program took 2nd place in Belarus among students and schoolchildren.

Unfortunately, such a large project (there are more than 120,000 lines of code and more than 140 class modules) we could not write in BASIC, and worked in C #

We currently want to do two things:
1. Create a small version of the Friend on this wonderful creation by Erel (B4X). Unfortunately, there is a problem of our ignorance of B4X: one of the important features of the Friend is easy multitasking (parallel functions, as in the Erlang language, can be launched in hundreds, and even on a remote machine with the Friend language).
But we don't know how independent actors (light processes) can be created on B4X!
2. We want to get a real CMS for android, which can be used to create real sites of low load, in the language of Friend.
Since Basic Erela is just wonderful for universal projects, we really hope to rewrite our algorithms to This Basic.
---------------------
With that said, we really want to look at your library code and try to parse it.

----------
Please explain why we cannot write private messages (where did the button go)?

Thank you.
Sincerely.
 

Star-Dust

Expert
Licensed User
You can find an example of the use of cookies in the first post.
Download SampleWebSocketPages and see how the CHAT page is managed in its module. You will see that the JSESSIONID Cookies are set and read to identify the session and the chatters.

I don't develop in C #, so I don't need to send me sources in this language. Please note that my library is entirely and exclusively written in B4X.

Furthermore, as I announced, I have already started developing a library for the automatic creation of Web pages through Templates and Wizards. (see here) I am still in the study phase and I am deepening the languages and frameworks currently available for WebApp (FrontEnd) to understand which is the best method.
So it does not seem appropriate to collaborate with a similar project, there would be a conflict of interest.

It is an excellent idea yours I wish you to succeed. Whatever questions you have to ask, you can use the forum (opening a new question thread) and ask the questions.
 
Last edited:

Star-Dust

Expert
Licensed User
1) We cannot write to you privately, therefore, in our version, browsers for some reason do not give private letter buttons. Or have we been foolishly looking for this button for a letter for a long time and do not find it?
With that said, we really want to look at your library code and try to parse it.

----------
Please explain why we cannot write private messages (where did the button go)
Full features are only available to those who have purchased a product or made a donation to Anywhere Software. Conversely, you cannot write privately and every public message is tested before being published, so a genre also arrives a day later. It is also not reported to me by the automatic alert.

With that said, the sources are not available for free at this time and honestly i think the source is of little use given the unfamiliarity with B4X
 
Last edited:

Darsiar

Member
hmmm ... This is a very unexpected attitude towards students that we didn't even think about. Because our experience of communication on the Internet is completely different.
Honestly, if they believe that it is right to do this in relation to students and schoolchildren from a country where the standard of living is 7 times lower than in any Europe and 12 times lower than in Israel, then we will try collectively, by the forces of our informal party, to collect the necessary amount for you, and after some time make a donation to you.
Please name the amount after which we will be able to receive the code of your libraries. And how can this money be sent to you from Belarus.
You can email us, can't you?
Send your price and we will start saving money ...
Thank you.
 

ilan

Expert
Licensed User
hmmm ... This is a very unexpected attitude towards students that we didn't even think about. Because our experience of communication on the Internet is completely different.
Honestly, if they believe that it is right to do this in relation to students and schoolchildren from a country where the standard of living is 7 times lower than in any Europe and 12 times lower than in Israel, then we will try collectively, by the forces of our informal party, to collect the necessary amount for you, and after some time make a donation to you.
Please name the amount after which we will be able to receive the code of your libraries. And how can this money be sent to you from Belarus.
You can email us, can't you?
Send your price and we will start saving money ...
Thank you.

you know that @Star-Dust is an individual developer right?
you need to understand that it takes a lot of time and effort to make such a library. and at the end, he is so kind to offer it for free and he also updated it several times to fix bugs but i really don't understand why people expect to get the free source of libraries/apps/games?!

it also does not matter where you are from and what your salary is. on most times we are talking about a few $ for the source (if the dev is interested in selling it)
so don't take it in a bad way and be offended it is a legitimate act to ask for few bucks when giving the source away. this will allow the developer to keep creating :)
 

Darsiar

Member
Okay.
We love your job.
We want to send you a few dollars, and we hope that after that you will kindly send us the source code of the library (how much you need to send, please specify in a personal letter).

But taking into account the policy of the site, we cannot write a private letter, since the sending of mail is blocked.
On the other hand, it is not clear what and how much need to pay to become a licensed user with all the features.
Perhaps we do not understand English well, but from the site documentation we still do not understand how we can do this? How, where and how much to pay to become full members of the forum team?
Also, it is not clear how we can transfer dollars or euros to the author of this library from our electronic card, which we use to buy small items in China?
Sincerely.
Alexander and students
 

EnriqueGonzalez

Well-Known Member
Licensed User
Hey
but from the site documentation we still do not understand how we can do this? How, where and how much to pay to become full members of the forum team?
Hey just a small donation will suffice, here yiu will find the info:

This is just for the b4x products support and for keeping the forum sane. After that you can send pm to other users.
 

Star-Dust

Expert
Licensed User
Okay.
We love your job.
We want to send you a few dollars, and we hope that after that you will kindly send us the source code of the library (how much you need to send, please specify in a personal letter).

But taking into account the policy of the site, we cannot write a private letter, since the sending of mail is blocked.
On the other hand, it is not clear what and how much need to pay to become a licensed user with all the features.
Perhaps we do not understand English well, but from the site documentation we still do not understand how we can do this? How, where and how much to pay to become full members of the forum team?
Also, it is not clear how we can transfer dollars or euros to the author of this library from our electronic card, which we use to buy small items in China?
Sincerely.
Alexander and students
I wrote above that to be a registered user and to be able to write privately you have to make a donation to Anywhere Software or buy one of their products.
In this forum each thread is dedicated to a topic, netiquette requires that a new thread be opened for each topic.
So if you want to know aspects about the donation or how to become a registered user open Specific thread do not write about this one concerning the library.

Finally, I have already indicated that I will not accept any donations from you students and I will not release my sources. Any donations made by you will be rejected
____________________________________________________________________________________________
Вышэй я пісаў, што, каб быць зарэгістраваным карыстальнікам і мець магчымасць пісаць у прыватным парадку, вы павінны зрабіць ахвяраванне Anywhere Software альбо купіць адзін з іх прадуктаў.
На гэтым форуме кожная тэма прысвечана нейкай тэме, у рамках этыкету патрабуецца адкрыць новую тэму для кожнай тэмы.
Таму, калі вы хочаце даведацца пра аспекты ахвяравання альбо пра тое, як стаць зарэгістраваным карыстальнікам, адкрыйце 'Канкрэтная тэма', не пішыце пра гэта адносна бібліятэкі.

Нарэшце, я ўжо адзначыў, што не буду прымаць ахвяраванні ад вас, студэнты, і не паведамлю свае крыніцы. Любыя вашы ахвяраванні будуць адхілены
 
Last edited:

Darsiar

Member
Your library is awesome!
REQUEST: Please remove the UploadProgress(success) event for uploading a file to the server. Or make it detachable. It is ideologically useless (the server runs unattended). However, this event greatly slows down the download of files!

1) After detailed consideration, we decided (with your permission) to embed it into our current project - into a universal CMS\REST- server with support for dynamic page generation, REST requests, and writing pages in the built-in scripting language of our production.
Experiments show that your library is stable. We ourselves added user registration and rights management by privilege groups to it. We also added a router mechanism to control access to dynamic site pages.
Your idea of dividing the server and site generator into different platforms is just amazingly clever!
We have already started developing a website generator for B4X. since we have extensive experience in creating a CMS with built-in dynamic objects and our own NOSqlL DB
We want to say that your project (library) is a real breakthrough for our project, and you are just great!

In the near future we will release the source codes of the project in which your wonderful library will be controlled by the built-in high-level scripting language.
This will be our gift to the community.
2) Special words to Erel: Recently Erel wrote to us that the translation of our huge project from C # to B4X is impossible, since it will require a titanic rewriting of the code.
Dear Dear Erel! You probably underestimated the effective genius of your B4X language !!!
We've almost done all the work! We made sure that with some simplifications, a project that took up 100,000 lines in C # can fit into 3,000 -4,000 lines of code in your language.
The presence of the library from "Stardust" finally pushed us towards rewriting.


Our thanks to the author of the Library and Erel!
 
Last edited:

Star-Dust

Expert
Licensed User
Your library is awesome!
REQUEST: Please remove the UploadProgress(success) event for uploading a file to the server. Or make it detachable. It is ideologically useless (the server runs unattended). However, this event greatly slows down the download of files!

1) After detailed consideration, we decided (with your permission) to embed it into our current project - into a universal CMS\REST- server with support for dynamic page generation, REST requests, and writing pages in the built-in scripting language of our production.
Experiments show that your library is stable. We ourselves added user registration and rights management by privilege groups to it. We also added a router mechanism to control access to dynamic site pages.
Your idea of dividing the server and site generator into different platforms is just amazingly clever!
We have already started developing a website generator for B4X. since we have extensive experience in creating a CMS with built-in dynamic objects and our own NOSqlL DB
We want to say that your project (library) is a real breakthrough for our project, and you are just great!

In the near future we will release the source codes of the project in which your wonderful library will be controlled by the built-in high-level scripting language.
This will be our gift to the community.
2) Special words to Erel: Recently Erel wrote to us that the translation of our huge project from C # to B4X is impossible, since it will require a titanic rewriting of the code.
Dear Dear Erel! You probably underestimated the effective genius of your B4X language !!!
We've almost done all the work! We made sure that with some simplifications, a project that took up 100,000 lines in C # can fit into 3,000 -4,000 lines of code in your language.
The presence of the library from "Stardust" finally pushed us towards rewriting.


Our thanks to the author of the Library and Erel!
Hi Students, I am aware that UploadProgresssuccess slows down the execution. It has been inserted for diagnostic purposes of some problems, since it is still in beta. Later it will be deleted or disabled.

I'm happy that the server is stable, I haven't done stress tests yet due to lack of time, I'm working on many other projects.
I am pleased to learn that you have added the functions you needed, as I wrote previously, the library is written in such a way that you can extend the server without having the sources.

You can use my library for any application. Every library shared here is under creative commons CC BY 3.0 license (see here) unless otherwise indicated by the developer. The only thing is not allowed to disassemble or recover the sources.
 
Last edited:

Erel

Administrator
Staff member
Licensed User
: Recently Erel wrote to us that the translation of our huge project from C # to B4X is impossible, since it will require a titanic rewriting of the code.
Dear Dear Erel! You probably underestimated the effective genius of your B4X language !!!
You misunderstood me, but it is not relevant to this thread.
 

Darsiar

Member
Dear Star Dust!
Can you (urgently) enter an accessible boolean variable into the server that blocks the loading progress event?
We will be very grateful!

Question: When the server opens a new request (Svr_Handle), is it already independent and parallel to the main thread?
From this event, can we launch a copy of the object of our script interpreter (dynamic page interpreter and script), and each instance will work without blocking other instances and the main thread?

The fact is that our scripting language, like the Ruby language, has its own multitasking at the kernel level. And we can split the time of hundreds of parallel threads into portions of the main stream time.
But we can also set a flag to each thread (an instance of the interpreter), which will say that there is no need to share time with other threads.
This is only if time sharing for concurrency has already been done by you in the Svr_Handle ...
Therefore, clarify - is it really, any relatively long process (procedure) launched from Svr_Handle will not block all its brothers, and the main thread?

Thank you!
Incredible respect!
 

Darsiar

Member
Suddenly there was an error in the compilation window, and no explanation:

Compilation of the generated Java code. Error
Can't find: C: \ Program Files (x86) \ Anywhere Software \ B4J \ libraries \ network.jar


Previously, they only compiled for Android, and everything was just fine!
The same thing happens when trying to compile your example for a desktop computer.

Disabling the library cuts remove the error.
 
Top