程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[web development] implement web server based on termux on Android mobile phones (Python, node.js, c/c++)

編輯:Python

Web Server series related articles are written as follows :

  1. 【Web Development 】Node.js Realization Web The server (http modular )
  2. 【Web Development 】Node.js Realization Web The server (express modular )
  3. 【Web Development 】Python Realization Web The server (Flask introduction )
  4. 【Web Development 】Python Realization Web The server (Flask test )
  5. 【Web Development 】Python Realization Web The server (Tornado introduction )
  6. 【Web Development 】Python Realization Web The server (Tornado+flask+nginx)
  7. 【Web Development 】Python Realization Web The server (FastAPI)
  8. 【Web Development 】Android The mobile phone is based on Termux Realization Web The server (Python、node.js)

List of articles

  • 1、 brief introduction
  • 2、 To configure Termux development environment
    • 2.1 install Termux
    • 2.2 management Termux The order of
    • 2.2 Install and update coreutils
    • 2.3 Install editor
    • 2.4 install Hacker's Keyboard
    • 2.5 install SSH
  • 3、Python Realization Web The server
    • 3.1 install Python
    • 3.2 function
  • 4、node.js Realization Web The server
    • 4.1 install node.js
    • 4.2 Write test code
    • 4.3 Write test code 2
  • 5、C/C++ Program development of
    • 5.1 install C/C++ Correlation Library
    • 5.2 function
  • 6、PHP Program development of
    • 6.1 install php library
    • 6.2 install nginx library
    • 6.3 install PHP-FPM library
  • 7 install mysql
  • Conclusion

1、 brief introduction

https://termux.com/
https://github.com/termux/termux-app#github

Termux - Apply to Android OS Terminal emulator application for , It can be extended through various packages .
Termux It's a free root Of linux Simulator .

Termux It's a Android Terminal emulation application , Used in Android Build a complete mobile phone Linux Environmental Science . Unwanted root jurisdiction Termux It can run normally .Termux Basic implementation Linux Many basic operations under . have access to Android Mobile phone erection Web The server tests .

  • Safe . Use from OpenSSH Of ssh The client accesses the remote server .Termux Combine the standard package with accurate terminal simulation in a beautiful open source solution .

  • Rich in functions . stay Bash、fish or Zsh and nano、Emacs or Vim Choose between .Grep Through your SMS inbox . Use curl visit API Endpoint and use rsync Store a backup of your contact list on a remote server .

  • Customizable . adopt Debian and Ubuntu GNU/Linux Known APT The package management system installs what you want . Why not install... From Git And sync your point file to start ?

  • Explorable . Have you ever sat on a bus and wondered tar Which parameters are accepted ?Termux The software packages available in are Mac and Linux The packages on the are the same - Install the man pages on your phone and read them in a session , Experiment in another session at the same time .

  • Including batteries . Can you imagine a better place than readline Driven Python The console is more powerful 、 A more elegant pocket calculator ?Perl、Python、Ruby and Node.js The latest versions of are available .

  • Prepare to expand the scale . if necessary , Connect a Bluetooth keyboard and connect your device to an external display - Termux Support keyboard shortcuts and complete mouse support .

  • Repairable . By using Clang compile Go、Rust、Swift or C File development , And use CMake and pkg-config Build your own project . If you encounter difficulties, you need to debug ,lldb/GDB and strace You can use .

2、 To configure Termux development environment

2.1 install Termux


2.2 management Termux The order of

linux Some common commands are as follows :

cd < Directory address > Open directory address
cp < file name > < Destination directory address > Copy to the destination directory address
mkdir < Folder name > New folder
rm < file name > Delete file
rm -rf < Folder name > Delete folder
ls Query the files and folders under this folder
chmod -x < The program name > Increase access to the program

except apt,Termux On this basis, it also encapsulates pkg command , Backwards compatible apt.pkg It will be executed once before running apt update, Ensure that the installed package is the latest version .

  • apt:
# Connect to remote warehouse , Get package information 
$ apt update
# Update locally installed packages 
$ apt upgrade
  • pkg:
pkg search <query> Search package
pkg install <package> Installation package
pkg uninstall <package> Uninstall package
pkg reinstall <package> Reinstall the package
pkg update Update source
pkg upgrade Upgrade package
pkg list-all List all packages available for installation
pkg list-installed List the packages that have been installed
pkg shoe <package> Displays the details of a package
pkg files <package> Displays the associated folder path of a package
#vim For the editor , You can change it to other editors , But it is highly recommended to use vim. Study vim It won't be difficult to operate , There are only a few commonly used commands , Just get used to it .
#curl Can be optimized termux Terminal interface , Download and install as appropriate .
#clang by C and C++ compiler .
#python Let's make some small programs for shooting , There are many other ways to play , Download and install as appropriate .
#gdb and cgdb For debugging tools , You can download and install as needed .
pkg install vim clang python gdb cgdb curl

  • Because the download speed of official source is slow , It is recommended to change the installation source to domestic source .
# Set the default editor 
$ export EDITOR=vi
# Edit source file 
$ apt edit-sources
or
$ vi $PREFIX/etc/apt/sources.list

Change the installation source to http://mirrors.tuna.tsinghua.edu.cn/termux, Save and exit .

see Linux Kernel version command ( The two methods ):

  1. cat /proc/version( It doesn't work here )
  2. uname -a( Here successfully executed )


Termux Support to install other Linux Distribution version .

  • Install various versions of the mobile phone linux:
termux-setup-storage # Get storage rights 
apt update
apt install x11-repo -y # download x11 Source 
apt update && apt upgrade -y
termux-change-repo # If the update is slow, you can replace Tsinghua source 
# download proot and proot-distro:
apt install proot proot-distro -y
proot-distro list
proot-distro install debian # Take advantage of the official proot-distro install Debian 
proot-distro login debian # Get into Debian System 
apt updateapt upgrade -y # Get into debian Update the source after the system 
apt install neofetch -y # install neofetch
neofetch
apt install sudo -y # install sudo
adduser test # Create a new user test
nano /etc/sudoers Send new users test Join in sudoers In the group

  • The following command can be used to view the phone's... From the command line IP Address .
apt install net-tools
ifconfig

  • Termux System test command
# install sl software package 
$ apt install sl
# function 
$ sl

2.2 Install and update coreutils

Coreutils The software package includes a complete set of basic shell Tools . yes GNU It provides a set of basic tool packages , Is a collection of these tools . It itself is dependent shell programmatic .

apt update && apt upgrade
apt install coreutils

2.3 Install editor

You can choose vim Or directly nano, Or other terminal text editor .

  • vim
apt install vim # Installation successful 
# or
pkg install vim # It can also be installed successfully 
pkg install vim-python # Give Way Vim Support Python Written plug-ins 
export EDITOR=vim # Set the default editor to Vim
 Insertion mode
i Enter insert mode from the current cursor
I Enter insertion mode , Place the cursor at the beginning of the line
a Append mode , Place the cursor after the current cursor
A Append mode , Place the cursor at the end of the line
o Add a new line under the current line , And enter insertion mode
O Add a new line to the current line , And enter insertion mode
Esc Exit insertion mode
 Exit editor
:w Write buffer to file , That is to save the modification
:wq Save the changes and exit
:x Save the changes and exit
:q sign out , If the buffer has been modified , Will prompt
:q! Forced exit , Abandon modification

Tips : How to use putty At the time linux vim Paste inside windows Clipboard stuff ?
Method 1 : Type... In normal mode “ :set mouse-=a”( Exclude Quotes )
Method 2 : edit ~/.vimrc file , Add the following code : if has(‘mouse’) set mouse-=a endif Method one opens each time vim It needs to be set once . Method 2: change the configuration file , Each start vim Can be pasted .
:set number The line number can be displayed .

  • nano
apt install nano # Installation failed 
# or
pkg install nano # Installation successful 

2.4 install Hacker’s Keyboard

It is inconvenient to write code with the input method commonly used in mobile phones , We often need tab、shift、ctrl And so on , therefore , We can install a special input method , Here you can choose Hacker’s keyboard.

https://github.com/klausw/hackerskeyboard

Use Android Equipment time , Do you lack the computer key layout you are used to ? This software keyboard has a separate number key 、 Punctuation marks and arrow keys for common positions . It's based on AOSP Gingerbread soft keyboard , So it supports multi touch of modifier keys .




Supported keyboard layouts include Armenian (Հայերեն)、 The Arabic language (العربية)、 English (en_GB)、 Bulgarian (български език)、 Czech (Čeština)、 Danish language (dansk)、Carpalx English ( Language “en-CX”)、 Dvorak English ( Language “en-DV”), English (QWERTY), Finnish language (Suomi), French (Français, AZERTY), German (Deutsch, QWERTZ), German Neo2 (Deutsch, Language “de-NE”), Greek (ελληνικά), Hebrew (עברית)、 Hungarian (Magyar)、 Italian (Italiano)、 Lao (ພາສາລາວ)、 Norwegian (Norsk bokmål)、 Persian (فارسی)、 Portuguese (Português)、 romanian (Română)、 Russian (Русский)、 Russian pronunciation (Русский) , ru-rPH), Serbian (Српски), Slovak (Slovenčina), Slovenian (Slovenščina)/ Bosnian / Croatian / Latin Serbian , Spanish (Español, Español Latinoamérica), Swedish language (Svenska), Tamil language (தமிழ்), Thai, (ไทย) 、 Turkish language (Türkçe) And Ukrainian (українська мова).

2.5 install SSH

The efficiency of typing on mobile phones is worrying , So I decided to start with Termux The last one is SSH service , Give Way PC The terminal can be connected to the mobile phone remotely . When the configuration is complete , To confirm the SSH Information about the connection . It should be noted that ,Termux Of sshd The service listens on by default 8022 On port .

# Mobile terminal 
pkg install openssh # install ssh
sshd # Open server , Allow other machines to access the current mobile terminal 
whoami # Check the login user name 
ifconfig # see ip
# Computer terminal 
ssh-keygen -t rsa # Generate the key 
# take id_rsa.pub copy To mobile phone ~/.ssh Catalog 
# Mobile terminal 
cat id_rsa.pub > authorized_keys # Add the key to the trust list 
# Computer terminal 
ssh -p8022 [email protected]


# install SSH service 
$ pkg install openssh
# Set the password 
$ passwd
# start-up sshd service 
$ sshd
# Access to native storage 
$ termux-setup-storage
# Check your mobile phone ip, Take the actual mobile phone ip Subject to 
$ ifconfig
=> 192.168.31.87
# Query current user 
$ whoami
=> u0_a184
# confirm ssh The listening port of the service 
netstat -ntlp | grep sshd
ssh [email protected] -p 8022
# stop it ssh
pkill sshd
# Set up ssh Auto on , There is no need to enter commands manually ( I haven't tried , Because I have an Android system for my old mobile phone , So don't bother trying )
echo "sshd" >> ~/.bashrc
  • Through the... On the computer Putty visit Android On the phone linux System :

    Through the... On the computer Putty visit Android On the phone linux Built on the system web The server , And then look at it android File data for :

  • Computer files uploaded to Android On the cell phone
scp -P 8022 /d:/test.png [email protected]:/data/data/com.termux/files/home
scp -P 8022 /d:/test.shp [email protected]:/sdcard/Download/
  • Computer side operation interface :
  • Mobile terminal output interface :

    Of course, you can also use a computer FileZilla Connect IP, port 8022, agreement SFTP, Connect with user name and password .

3、Python Realization Web The server

3.1 install Python

# install python3. If you need to install python2, execute pkg install pyton2.
$ pkg install python
# Or installation python: Training python
pkg install python -y
# upgrade pip3: Easy to install some python library 
python -m pip install --upgrade pip -i https://pypi.tuna.tsinghua.edu.cn/simple some-package

3.2 function

# start-up HTTP service .
$ python -m http.server 8080

On a desktop computer edge Browser access above anroid Built by mobile phones web The servers are as follows :

4、node.js Realization Web The server

4.1 install node.js

apt install nodejs

4.2 Write test code

mkdir test
cd test
touch server.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {

res.end('hello 2022, Xiaomu who loves reading !');
});
server.listen(port, hostname, () => {

console.log(`Server running at http://${
hostname}:${
port}/`);
});
  • function
node server.js

4.3 Write test code 2

http-server It's a simple zero configuration command line HTTP The server , be based on nodeJs.

  • Use npm/cnpm install http-server
npm install http-server -g
  • function
http-server -a 0.0.0.0 -p 3000
or
http-server


On a desktop computer edge Browser access above anroid Built by mobile phones web The servers are as follows :

5、C/C++ Program development of

5.1 install C/C++ Correlation Library

pkg install vim clang python gdb cgdb

5.2 function

open vim To write c Code , as follows :

There are three ways to compile code :

clang -o mytest mytest.c
gcc -o mytest mytest.c
g++ mytest.cpp -o mytest

6、PHP Program development of

6.1 install php library

pkg install php


start-up PHP built-in WEB The server :

php -S 0.0.0.0:8081



adopt vim create a file test.php:

<?php phpinfo();?>

6.2 install nginx library

(Nginx It's a high performance web The server , Often with php Cooperate to analyze and build the website )

# install nginx: build web The server 
pkg install nginx


(1) start-up Nginx

nginx

(2) use pgrep Command to view the terminal number ( have a look nginx Is it activated )

pgrep nginx


At the computer edge Visit the web address on the browser :

http://192.168.31.87:8080

From the content returned from the web page, we can see nginx Normal start .

6.3 install PHP-FPM library

nginx And php It's all installed , The next step is to link the two programs together .
nginx It's a static web The server , It can only be resolved html This kind of static file , about php This dynamic language is powerless , So we need to php Request to hand over to php Interpreter Handle , But how can we distinguish html And php What about the documents ?
php-fpm yes nginx And php An interactive bridge between .

# install php-fpm
pkg install php-fpm

  • To configure php-pfm
    php-pfm The configuration file is in the absolute path /data/data/com.termux/files/usr/etc/php-fpm.d/www.conf, adopt vim modify :
vim $PREFIX/etc/php-fpm.d/www/conf


Put... In the picture above listen Revised as follows :

  • To configure Nginx
    Nginx The configuration file of is in the absolute directory /data/data/com.termux/files/usr/etc/nginx/nginx.conf, use vim open nginx.conf file :
vim $PREFIX/etc/nginx/nginx.conf




New test page info.php, As shown in the figure below :

# Start the program 
php-fpm
nginx

# see 8080 The process whose port is occupied 
lsof -i:8080
# kill Command to kill the process 
kill -9 9622

7 install mysql

pkg install mariadb
# If the installation fails, it may be because there is no name my.cnf.d The catalog of 
cd /data/data/com.termux/files/usr/etc
mkdir my.cnf.d
# If my.cnf.d directory already exists , Do nothing , Then go back to the home page :
cd $home
# Once the directory is created ( If the directory does not exist ), We will execute the following command :
# initialization MariaDB Data directory , And create... In the database The system tables mysql
mysql_install_db
# Optional , But the advice : Safe MariaDB
mysql_secure_installation

start-up mysql:

mysqld
# or mysqld_safe And root Run with users ;“&” Number will run in the background .
mysqld_safe -u root &

Access database :

mysql -u root -p
# or By default , There is no password 
mysql

start-up MySQL The remote access , Get into mysql:

# Create a user who can log in remotely 
CREATE USER 'tomcat'@'%' IDENTIFIED BY '123456';
GRANT ALL privileges ON *.* TO 'tomcat'@'%';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'IDENTIFIED BY '123456' WITH GRANT OPTION;
flush privileges;

among root It's the login user name ,123456 Is the database login password , Refresh the configuration after setting ;



stop it MariaDB The server :

# To stop MariaDB The server 
pkill mysql
# To find the process to execute ID:
ps aux | grep mysql
# Have ID after , Please kill them :
kill -9 15423

Conclusion

If you find the method or code a little useful , You can praise the author , Or a cup of coffee ;╮( ̄▽ ̄)╭
If you feel that the method or code is not good //(ㄒoㄒ)//, Just leave a message in the comments , The author continues to improve ;o_O???
If you need customized code development for related functions , You can leave a message to the author ;(*◡‿◡)
Thank you for your support !( ´ ▽´ )ノ ( ´ ▽´)っ!!!




  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved