Documentation

On this page

Download full book (text)

# **Chapter 22: NativeGate — WebSocket Apps, Child Processes, and Mobile/Cloud** > **Prerequisites:** Chapters 13 (jsServer) and 21 (ConsoleGate — NativeGate > inherits its shell API) > **Try it:** UI page loads anywhere — > `http://localhost/SartajPhpDoc/ex14nativeui.html` > (`apps/examples/Ex14nativeui.gate.php` + `appsn/examples/Ex14native.gate.php`). > The WebSocket features need **SphpServer** (not Apache): > > ```bat > sphpdesk\sphpserver\sphpserver-win.exe --proj .\ --port 8000 --host 127.0.0.1 > ``` --- ## **22.1 What NativeGate Is** A `NativeGate` (`\Sphp\Gates\NativeGate`) is a **long-lived process** with a WebSocket to the browser, instead of a per-request Gate: | | BasicGate | NativeGate | |---|-----------|------------| | Lifetime | one request | process until quit | | Transport | HTTP POST | WebSocket (push both ways) | | Talks to OS | only via helpers | `callSync`, child processes | | jsServer | response per request | `sendTo()` / `sendAll()` anytime | Use it for live dashboards, chat, hardware/ML bridges — and it is the same developer model the framework uses for **Cloud** apps: Cloud ≡ NativeGate + SphpServer, no separate framework mode. ## **22.2 The UI Side: SocketOutput + callNativeGate** The browser page is an ordinary BasicGate + Front. Two pieces (tested page `ex14nativeui_main.front`): ```html <!-- live log stream component --> <div id="div1" runat="server" path="slibPath/comp/server/SocketOutput.php" style="max-height:320px; overflow:auto; font-size:12px;"></div> <script type="text/javascript"> function startGate(){ $("#txtstatus").text("Starting NativeGate…"); callNativeGate("ex14native", "startme", "", {}); } function runGateShell(){ var cmd = $("#txtcmd").val() || "php -v"; callNativeGate("ex14native", "shell", "", {cmd: cmd}); } function onChildQuit(){ $("#txtstatus").text("Python child exited — click Start again"); } </script> ``` `callNativeGate(gate, event, evtp, data)` is the WebSocket twin of `sendAjax` — same event routing, but it reaches the **running** Gate process. `SocketOutput` renders everything the Gate pushes. The component-level twin is `fun-submitWS` (Chapter 13). ## **22.3 The Gate Side: Process, Child, Streams** `appsn/examples/Ex14native.gate.php` (source tested; WS runtime needs SphpServer) shows the full pattern: ```php <?php class Ex14native extends \Sphp\Gates\NativeGate { public function onstart() { // one process per WS session (default) — easy to retest after edits // setGlobalGate() → ONE process for ALL tabs/users until server stops // $this->setGlobalGate(); $this->createProcess($this->pythonPath, array('-u', $this->childScript), 'demo1'); // spawn Python child $this->jsServer->addJsonHtmlBlock('txtstatus', 'NativeGate + Python child starting…'); $this->sendTo(); // push to this session } /** Browser → Gate: shell command on the Gate process itself */ public function page_event_shell($evtp) { $bdata = $this->client->request('bdata'); $cmd = is_array($bdata) && isset($bdata['cmd']) ? trim((string) $bdata['cmd']) : ''; $out = ''; $this->callSync($cmd, $out, 'shell'); // ConsoleGate API $this->jsServer->addJsonReturnBlock(trim((string) $out)); $this->sendTo(); } /** Browser → Gate → Python child */ public function page_event_pyshell($evtp) { $this->childCom->callProcess('shell', array('cmd' => $cmd)); } /** Python child → Gate (child calls callSphpEvent("onshell", data)) */ public function page_event_c_onshell($evtp, $data) { $this->jsServer->addJsonReturnBlock('child onshell exit=' . $evtp); $this->sendTo(); } /** Any stdout/stderr line from the child */ public function onconsole($data, $type) { $this->jsServer->addJsonReturnBlock('log: ' . trim((string) $data)); $this->sendTo(); } public function onwscon($conobj) { /* browser connected */ } public function onwsdiscon($conobj) { $this->sendOthers(); } // broadcast to rest public function oncquit() { $this->ExitMe(); } // child exited → quit } ``` The naming conventions are the whole API: | Direction | Mechanism | |-----------|-----------| | Browser → Gate | `callNativeGate(gate, evt, evtp, data)` → `page_event_evt` | | Gate → browser(s) | `jsServer` blocks + `sendTo()` (this session) / `sendOthers()` (broadcast) | | Gate → child | `$this->childCom->callProcess('cmd', $args)` / `sendCommand('quit')` | | Child → Gate | child calls `callSphpEvent("name", data)` → `page_event_c_name` | | Child stdout/err | `onconsole($data, $type)` | | Lifecycle | `onwscon`, `onwsdiscon`, `onquit`, `oncquit` | **Process model decision** (from the Gate's own comments): default = one process per WS session (code edits retest by reconnecting); `setGlobalGate()` = one shared process for all users (chat rooms, live classrooms) — but PHP/Python edits then need a full SphpServer restart. ## **22.4 MobileGate — The Same Gates in a Phone App** `mobileapp/` is a second project whose Index Gate extends `\Sphp\Gates\MobileGate` (tested generator): ```php <?php // mobileapp/apps/Index.gate.php (excerpt) class Index extends \Sphp\Gates\MobileGate { public function page_new() { $this->mobappname = "SphpDoc Mobile Demo"; $this->minSdkVersion = "26"; $this->targetSdkVersion = "34"; $this->addAndroidSetting("permission", '<uses-permission android:name="android.permission.INTERNET"/>'); $this->addAndroidSetting("dependency", 'implementation("androidx.appcompat:appcompat:1.7.0")'); SphpJsM::addBootStrap(); $this->addDistLib($this->resourcePath . "/jslib/twitter/bootstrap5"); $this->addDistLib($this->resourcePath . "/jslib/onsen"); // SPA navigator $this->addCppDir(__DIR__ . "/cpp/nativedemo"); // optional NDK/C++ $this->addPage(new Sphp\Tools\FrontParser($this->myPath . "/fronts/page2.front")); } } ``` Run from `mobileapp/`: ```bat php -f start.php -- --gate index ``` It generates a **WebView app**: `www/` (HTML built from your Fronts) plus an **Android Studio project** (`app/`). Inside the app, `sendAjax` / `getAjaxReturn` / NativeGate WS work against your configured server — so everything from Chapters 13-18 carries over; the phone is another browser. ## **22.4a Inside the Generated Project — KotlinGate and SJS** The mobile app is **not a wrapper**: PHP builds the UI, Kotlin runs native logic on the device, and one shared project directory holds both. The tested `mobileapp/` layout: ``` mobileapp/ ├─ apps/ │ ├─ Index.gate.php # MobileGate — settings + page list (22.4) │ ├─ fronts/ # .front designs → compiled into www/ HTML │ ├─ sjs/ # SJS files — server-side-embedded JS per front │ ├─ kotlin_apps/ # KotlinGate classes (the phone-side "Gates") │ │ ├─ IndexGate.kt │ │ └─ NativeLib.kt # JNI wrapper for the C++ lib │ ├─ android/ # MainActivity.kt, config.xml, res/, libs/ │ └─ cpp/nativedemo/ # optional NDK/C++ sources ├─ www/ # GENERATED web assets (open in WebView) ├─ app/ # GENERATED Android Gradle project (build APK) ├─ build.gradle.kts, settings.gradle.kts, gradlew # plain Gradle build └─ start.php, comp.php, reg.php, masters/ # ordinary SartajPhp files ``` Three developer surfaces: **1. SJS (`apps/sjs/*.sjs`)** — one file per front; functions named `comp_{id}_{event}` are embedded into the page server-side, so JS event code lives with the project instead of inline in HTML: ```javascript // apps/sjs/index_main.sjs function comp_home_init(eventer){} function comp_home_show(eventer){} ``` **2. KotlinGate (`apps/kotlin_apps/*.kt`)** — the phone-side twin of a PHP Gate: same lifecycle (`onstart`, `page_new`), same `page_event_*` routing, same `JSServer` blocks as jsServer (Chapter 13). The browser calls it with `callKotlinGateEvent(gate, event, evtp, data)` — the local twin of `callNativeGate`: ```kotlin // apps/kotlin_apps/IndexGate.kt (excerpt, tested) class IndexGate : KotlinGate() { suspend fun page_event_nativeAdd(evtp: String) { val sum = NativeLib.addInts(dataOptInt("a", 0), dataOptInt("b", 0)) JSServer.addJSONHTMLBlock("spnNative", "C++ addInts = $sum") JSServer.callJsFunction("onNativeResult", JSONObject().put("result", sum)) JSServer.flush() } } ``` **3. Native code (`apps/cpp/`)** — C/C++ compiled by Gradle/CMake, exposed to Kotlin through a `System.loadLibrary` wrapper (`NativeLib.kt`), reachable from the UI through the KotlinGate above. So the request flow inside the app mirrors the web chapters: WebView UI → SartajPhp router → **KotlinGate** (device) or `sendAjax` to your **PHP Gate** (server) — and heavy native work goes Kotlin → JNI → C++. Build the APK with Android Studio (or `gradlew assembleDebug`) — no Cordova, no Electron, no code generation step beyond `php -f start.php -- --gate index`. ## **22.5 Cloud = NativeGate + SphpServer** For developers there is **no separate Cloud framework mode**: a Cloud app is a NativeGate running under SphpServer (or in a container), exactly as in 22.3. Your Gate code does not change between laptop, server, and cloud — only the deployment around it (which is outside this book's scope). ## **22.6 Verify It Yourself** 1. Apache: `ex14nativeui.html` renders (buttons + log panel) — WS calls need SphpServer, so they no-op here 2. Start SphpServer: `sphpdesk\sphpserver\sphpserver-win.exe --proj .\ --port 8000 --host 127.0.0.1` 3. Open `http://127.0.0.1:8000/ex14nativeui.html` → **Start** → status "Gate ready", log shows `startme` 4. **Gate demos** → `php -v` etc. run on the Gate process, output streams live 5. **Python demos / Ping Python** → commands go to the Python child (`appsn/examples/python/child_demo.py`) and return via `page_event_c_*` 6. **Quit child** → `oncquit` → status updates, Start re-enables 7. Mobile: `cd mobileapp && php -f start.php -- --gate index` → inspect generated `www/` + `app/` (open in Android Studio to build an APK) --- **Previous:** [Chapter 21 — ConsoleGate](chapter21.md) · **Next:** [Chapter 23 — Component Internals](chapter23.md)