当前位置:网站首页>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 .

原网站

版权声明
本文为[hi_ LeTian]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010623365485.html

随机推荐