当前位置:网站首页>Design of a simple embedded web service application
Design of a simple embedded web service application
2022-06-12 04:55:00 【hi_ LeTian】
A simple embedded WEB Business application design
Mainly for the previous products WEB Application design refactoring , Separate the business from something , Convenient maintenance , It's simple , Note that this does not mean writing WEB Of the service program .
Tools
goahead
json-c
jquery
Data interaction
WEB The service interacts with the main application
WEB The service process and the application process are in the same embedded system , The interactive use of two processes UNIX Domain UDP Party test communication , The main data is ,WEB Front end data request , Data submission or control command , All data are used json The format of transmission .
WEB Services and WEB Front end interaction
WEB Front-end HTML All requests are made through goahead Processed , On the data , We use it AJAX transmission JSON The way ,goahead adopt UDP The service is transferred to the main application , After the main application is processed, it returns to goahead, Then respond to WEB front end .
The reason to use UNIX Domain UDP signal communication , One is speed , And reliable ,JSON The data exchanged is not too large , Two-way communication , Simple , There is no need to separate the package from the package .
WEB Server side
Web The service uses open source goahead This tool , It is relative to the WEB The front end is a server , In terms of our main application, it is another UNIX Domain UDP client .
WEB Server initialization
Goahead The initialization of can be seen in its example , In fact, I am not familiar with this tool , Change it in the example it provides , There is one in its initialization operation initWebs The process of , Some necessary parameters are set here , Such as the default web page , For example, my settings are index.html Is defined by a macro :
#define WEBS_DEFAULT_HOME T("index.html") /* Default home page */
#define WEBS_DEFAULT_PORT 80 /* Default HTTPport */
#defineWEBS_DEFAULT_SSL_PORT 433 /* Default HTTPSport */
The default home page is defined respectively , port .
To communicate with the main application , It uses UNIX The domain of UDP The way , So in goahead We're going to initially create a socket To interact with the main application .
In a suitable place , Define a Web_Client_init, Its function is to initialize and create a UNIX The domain of UDP socket nothing more , So in initWebs The calling procedure : Web_Client_init().
In a suitable place , Define a int Web_Client_Send(char* buf, int len, char* recvbuf, int* maxlen), Use it to put WEB The front-end data is forwarded to the main application , Receive the response from the main application at the same time .
stay goahead Inside receiving WEB From the front AJAX request json data , Do the following actions :
Set up a URL Processing of requests :
websUrlHandlerDefine(T("/ajax/json_data"),NULL, 0, ajax_json_data, 0);
This fruit URL by http://xxxx/ajax/json_data In this way URL Data from here , All to ajax_json_data Processed . Such as my following handling ,
#define RECV_BUF_LEN 2048
static charRECV_BUF[RECV_BUF_LEN];
int ajax_json_data(webs_t wp, char_t *urlPrefix, char_t *webDir, int arg,
char_t *url, char_t *path, char_t *query)
{
int ret;
char* data = websGetVar(wp,T("data"),"");
int len = strlen(data);
//ret = WebMsg_Send(data, len);
//char recvbuf[1024] = {0};
int recvlen = RECV_BUF_LEN;
RECV_BUF[0]= 0;
ret= Web_Client_Send(data, len, RECV_BUF, &recvlen);
if(ret == 0)
{
if(recvlen == 0)
{
websWrite(wp,T("{status:'failed', data:'Server nodata!'}"));
}else{
websWrite(wp,RECV_BUF);
}
}else{
websWrite(wp,T("{status:'failed'}"));
}
websDone(wp,200);
return 1;
}
commonly JSON The requested data of is not very large , Pay attention to the allocation of space , The above procedure is to call Web_Client_Send Send the data to the main application , After the main application is processed , Also returned is JSON The answer in the format , After getting the response from the main application, pass websWrite Write back to WEB front end , Be careful websGetVar How to get the data , I'm looking for someone named ”data” Of , This is in WEB In the web page JS The definition of , The reason is our JS This is how the code is written :
functionajaxActionWrap(actionData, callback)
{
$.post(URL_AJAX_ACTION,
{
data: actionData,
},
function(data, status){
if(callback)
callback(data, status)
}
);
}
When this is done , our WEB The server is finished , Its function is to transmit data , Divide it from the business .
Main application
A task of the main application is to receive WEB From the service WEB The front end requests .
Create a UNIX Domain UDP service . For example, we create a method to initialize and start the service in a suitable place : Web_Server_Init(), So you can receive WEB The request of .
Another task is to WEB Of AJAX JSON The processing of the request responded to .
Different JSON call , For different businesses , So we define a structure that records different business processes :
such as :
typedef int (*JsonActionProc)(char* data, void* jsonobj,AjaxActionProcCallBack cb);
typedef struct_WebAjaxAction{
char* actionName;
JsonActionProc actionProc;
}WebAjaxAction;
actionName Is the identification of the corresponding processing method , Such as WEB The front end transmits a message like this JSON Data come here :
{"action":"wifi_status","data":{"p1":1,"p2":2}}
that wifi_status It's corresponding to actionName.
Record registration of each json Inside action Call the process , Such as :
static WebAjaxActionwebAjaxActionList[] = {
{ "wifi_status",wifi_status},
{ "wifi_scan",wifi_scan},
{ "wifi_get_aplist",wif_get_aplist},
{ "wifi_conn",wifi_conn},
{ "wifi_getAplist",wifi_getAplist},
};
image wifi_status,wifi_scan… These are the identification of the calling method , This has to do with WEB The front-end negotiation is good , bring into correspondence with .
actionProc The parameter is the corresponding calling method .
The above process , It's like WEB Pass a JSON Data come here , It has a corresponding actionName, adopt actionName Find the corresponding business method ,JSON There will also be some parameters in the , hold JSON The data in the , Just call the corresponding business method , At the same time, the processed data is passed through WEB Returned by the server WEB front end .
From the above process , Come on , call recvfrom After receiving the datagram , Call a procedure , from webAjaxActionList Find the corresponding processing method in , Call the handler , After the treatment method is completed , Pass the data to be returned through sendto Back to WEB Server side , And then back WEB front end . The whole process is over .
WEB front end
Complete the above ,WEB The front end can be easily called , When HTML Show after loading , Re pass AJAX The way , use JSON Format to call data .
If I get one WIFI Connection state of , Of course , The interaction of JSON Data needs to be WEB The front end and the back end of the main application should be negotiated , In what format , Let's say mine is :
{"action":"wifi_status"}
Indicates that the method called is wifi_status
For example, the following related methods :
/* obtain WIFI Connection status */
functiongetWifiStatus()
{
var data ='{"action":"wifi_status"}';
ajaxActionWrap(data,getWifiStatusCallBack);
}
functionajaxActionWrap(actionData, callback)
{
$.post(URL_AJAX_ACTION,
{
data: actionData,
},
function(data, status){
if(callback)
callback(data,status)
}
);
}
functiongetWifiStatusCallBack(data, status)
{
if(status != "success")
{
alert("get wifi statusfailed!\n");
return;
}else{
var jobj = eval(data)
if(jobj)
{
$("#wifiCurAp").html(jobj[0].wifi_status.ssid);
if(jobj[0].wifi_status.status== 1)
$("#wifiCurStatus").html(" Connected ");
else
$("#wifiCurStatus").html(" Unconnected ");
}else{
$("#wifiCurStatus").html(" Unconnected ");
}
}
}
On the back end , It will find wifi_status Corresponding processing method of , After processing, return to the defined JSON data format ,WEB The front end is displayed again .
Last
Through the above processing , For the main application , It separates all the business-related things , In the corresponding processing method ,WEB The server is only responsible for transmitting data ,WEB Front end by AJAX Transmission by JSON Data and reception , adopt JS Script control .
When adding a new business , Just modify WEB Front-end JS Script , The main backend registers the processing method .
notes : Yes WEB Application only knows a little , A little note about the above implementation :
1:JS It's better not to use... In the script eval Convert data to generate object , unsafe , It can be used jQuery The corresponding tool in .
2:AJAX Request authentication for , Be sure to add , Like the above application , A better way can be added to WEB Server side ajax_json_data in , When requesting back-end applications , Check it out , See many products ,AJAX The request does not have authentication permission at all .
边栏推荐
- Gao Xiang slam14 notes on three Lie groups and Lie algebra
- Redis learning notes (continuously updating)
- Pytorch was reported by a large number of netizens that torchrec, a new library, was "born" and has a large scale
- What is reverse repurchase of treasury bonds? Is the reverse repurchase of treasury bonds safe?
- L1-065 "nonsense code" (5 points)
- [backtracking based on bit operation] queen n problem 2
- Longest palindrome string
- Font conversion optimization
- Why is Julia so popular?
- How to use union all in LINQ- How to use union all in LINQ?
猜你喜欢

Some problems of silly girl solved

2022 examination questions and online simulation examination for safety management personnel of hazardous chemical business units

How to deploy PostgreSQL as a docker container

Operation of simulated examination platform for theoretical question bank of G2 utility boiler stoker in 2022

How to count the total length of roads in the region and draw data histogram

Let me tell you the benefits of code refactoring

When the build When gradle does not load the dependencies, and you need to add a download path in libraries, the path in gradle is not a direct downloadable path

Qinglong wool - Kaka

kali_ Change_ Domestic source

Redis learning notes (continuously updating)
随机推荐
Realease package appears – missing type parameter
How to quickly reference uview UL in uniapp, and introduce and use uviewui in uni app
Asp. Net core EF value conversion
22-2-28 there are many things to do at work today, ETH analysis
Spatial distribution data of national multi-year average precipitation 1951-2021, temperature distribution data, evapotranspiration data, evaporation data, solar radiation data, sunshine data and wind
mysqld: Can‘t create directory ‘D: oftinstall\mysql57 (Errcode: 2 - No such file or directory)
[efficient] the most powerful development tool, ctool, is a compilation tool
How to use union all in LINQ- How to use union all in LINQ?
Soil type, soil texture, soil nutrient and change data, soil organic matter, soil pH, soil nitrogen, phosphorus and potassium
Detailed explanation of Command Execution Vulnerability
Find missing sequence numbers - SQL query to find missing sequence numbers
Report on the current market situation and future development trend of adhesive industry for radar and ultrasonic sensors in the world and China 2022 ~ 2028
Kwai opens a milestone activity for fans to record every achievement moment for creators
Applet pull-down load refresh onreachbottom
SQL injection upload one sentence Trojan horse (turn)
Day17 array features array boundary array application traversal array multidimensional array creation and traversal arrays operation array bubble sort
IC验证中的force/release 学习整理(6)研究对 wire 类型信号的影响
Interview must ask: summary of ten classic sorting algorithms
JWT learning and use
New year news of osdu open underground data space Forum