Libwebsockets Interface Parsing

Source: Internet
Author: User

void Lws_set_log_level (int level, void (*log_emit_function) (Int. level, const char *line));

Lws_set_log_level ()-Set the logging bitfield (bit field)
Param level:or together the Lll_ debug contexts you want output from
Param Log_emit_function:null to leave it as it are, or a user-supplied function to perform log string emission instead of The default stderr (standard output) one.

Log level defaults to "err", "warn" and "notice" contexts enabled and emission on stderr. If stderr is a TTY (according to Isatty ()) then the output was coloured according to the log level using ANSI escapes. (outline)


struct Lws_context *lws_create_context (struct lws_context_creation_info *info);

Lws_create_context ()-Create the WebSocket handler (manager)

param info:pointer to struct with parametersthis function creates the listening socket (if serving) and takes care of All initialization in one step (create socket and complete a series of initial chemical work)

If option lws_server_option_explicit_vhosts is given, no Vhos T is created; You ' re expected to create your own vhosts afterwards using Lws_create_vhost () .  Otherwise a vhost named "Default" is Also createdusing the information in the vhost-related members, for compatibility (create Vhost, special case Call Lws_create_vhost ())

After initialization, it returns a-struct Lws_context * that represents the this server. After calling, user code needs to take care of calling Lws_service () with the context pointer to get the server ' s sockets  Serviced. This must is done with the same process context as the initialization call. (after initialization, loop calls Lws_service () to get the service) The protocol callback functions is called for a handful of events including HTTP requests coming in, WebSocket connection s becoming established, and data arriving; It ' s also called periodically to allow async transmission. (Connection, request send, Receive Message Call protocol callback function, callback function is called periodically in order to achieve the effect of asynchronous transfer)

HTTP requests is sent always to the first protocol in Protocol, since at that time WebSocket protocol have not been Negoti  Ated. Other protocols after the first one never see any HTTP callback Activity. (HTTP requests are only available at the first interaction, at which time WS has not reached an agreement, then no HTTP headers are required for other protocols)

The server created is a simple HTTP server by default; Part of the websocket are upgrading this HTTP connection to a websocket one. (WS is an enrichment of the HTTP service)

This allows the same server to provide files like scripts and favicon images or whatever over HTTP and dynamic Data over W Ebsockets all on one place; They ' re all handled in the user callback. (In the user callback, provide scripting language, pictures and other data)


int Lws_service (struct lws_context *context, int timeout_ms);

Analytical:

Polllws_service ()-Service any pending (upcoming) WebSocket activity

Param Context:websocket Context (contextual)

Param timeout_ms:0 means return immediately if nothing needed service otherwise block and service immediately, return ing after the timeout if nothing needed service.

This function deals with any pending websocket traffic (interactive), for three kinds of event. It handles these events on both server and client types of connection the same.
1) Accept new connections to our context ' s server (accept connection)
2) Call the receive callback for incoming frame data received by server or client connections. (Message callback)

You need to call this service function periodically to all the above functions to happen; If your application is single-threaded you can just call it in your main event loop. (Loop calls the function)

Alternatively you can fork a new process the asynchronously handles calling this service in a loop. In so case you is happy if this call blocks your thread until it needs to take care of something and would call it with  A large nonzero timeout. Your Loop then takes no CPU while there is nothing happening. (It is best to call this function with a heavy thread)

If you're calling it in a single-threaded app, you don't want it to wait around blocking other things in your loop from H Appening, so-would call it with a timeout_ms of 0, so it returns immediately if what is pending, or as soon as it s Ervices whatever was pending. (The timeout is best set to 0)


struct LWS_CLIENT_CONNECT_INFO

struct Lws_client_connect_info {
struct Lws_context *context; /**< LWS context to create connection in * *
const char *address; /**< remote Address to connect to */
int port; /**< remote port to connect to */
int ssl_connection; /**< Nonzero for SSL */
const char *path; /**< URI Path */
const char *host; /**< content of Host header */
const char *origin; /**< content of Origin header */
const char *protocol; /**< List of WS protocols we could accept */
int ietf_version_or_minus_one; /**< deprecated:currently leave at 0 or-1 */
void *userdata; /**< if non-null, use this as WSI user_data instead of malloc it */
const void *client_exts; /**< UNUSED ... provide in info.extensions at context creation time */
const char *method;
/**< if non-null, do this HTTP method instead of Ws[s] upgrade.
* use ' GET ' to is a simple HTTP client connection */
struct LWS *parent_wsi;
/**< If another WSI is responsible for this connection, give it here.
* This is a used to make sure if the parent closes so does any
* Child connections first. */
const char *uri_replace_from;
/**< if Non-null, when the this string was found in URIs in
* text/html content-encoding, it ' s replaced with uri_replace_to */
const char *uri_replace_to;
/**< See Uri_replace_from */
struct Lws_vhost *vhost;
/**< vhost to bind to (used to determine related ssl_ctx) */
struct LWS **pwsi;
/**< if not NULL, store the new WSI here early in the connection
* process. Although we return the new WSI, the call to create the
* Client connection does progress the connection somewhat and May
* Meet an error that would result in the connection being scrubbed and
* NULL returned. While the WSI exists though, he may process a
* Callback like Client_connection_error with his wsi:this gives the
* User callback A to identify which wsi it's that faced the error
* Even before the new WSI is returned and even if ultimately no WSI
* is returned.
*/
const char *iface;
/**< NULL to allow routing on any interface, or interface name or IP
* To bind the socket to */


/* Add new things just above here---^
* This was part of the ABI, and don ' t needlessly break compatibility
*
* The below is to ensure later library versions with new
* Members added above would see 0 (default) even if the app
* was not built against the newer headers.

*/void *_unused[4];

};


struct LWS * Lws_client_connect_via_info (struct lws_client_connect_info * ccinfo);

Lws_client_connect_via_info ()-Connect to another WebSocket server
param Ccinfo:pointer to Lws_client_connect_info struct
This function creates a connection to a remote server using the

Information provided in Ccinfo.


void Lws_context_destroy (struct lws_context *context);

Lws_context_destroy ()-Destroy the WebSocket context

Param Context:websocket Context

This function closes any active connections and then frees the context. After calling this, any further use of the context is undefined


Implementation code:

struct Session_data {
int FD;
};

static int Ws_service_callback (
struct LWS *wsi,
Enum lws_callback_reasons reason, void *user,
void *in, size_t len)

{

Switch (reason) {case lws_callback_client_established:
printf ("[Main Service] Connect with server success.\n");
Connection_flag = 1;
Break

Case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
printf ("[Main Service] Connect with server error.\n");
Destroy_flag = 1;
Connection_flag = 0;
Break

Case lws_callback_closed:
printf ("[Main Service] lws_callback_closed\n");
Destroy_flag = 1;
Connection_flag = 0;
Break

Case Lws_callback_client_receive:

printf ("[Main Service] Client recvived:%s\n", (char *) in); if (Writeable_flag)
Destroy_flag = 1;

Break Case Lws_callback_client_writeable:
printf ("[Main Service] on writeable is called. Send Byebye message\n ");
Websocket_write_back (WSI, "byebye! See you later ",-1);
Writeable_flag = 1;
Break

Default
Break
}

return 0;
}


Static lws_context* S_ptcontext;
static struct Lws_protocols protocols[] = {
{"Lws-mirror-protocol", Ws_service_callback, 0, 1024 * 32},
{null, NULL, 0, 0}/* End */
};

#define Port_len 8
#define Session_len 24

String Combineipandport (std::string strIP, int wport, int dwtype)
{
std::string strsession (StrIP);
Char Achport[port_len] = {0};
sprintf_s (Achport, Port_len, ":%d|%d", Wport, dwtype);
Strsession.append (Achport);
return strsession;
}

Static lws_context* Createcontext ()
{
Lws_set_log_level (0xFF, NULL);
lws_context* plccontext = NULL;

Lws_context_creation_info Tcreateinfo;
memset (&tcreateinfo, 0, sizeof tcreateinfo);

Tcreateinfo.port = Context_port_no_listen;
Tcreateinfo.protocols = Protocols;

Plccontext = Lws_create_context (&tcreateinfo);

return plccontext;
}

static void Connect (string url, string &strserverip, int wport, int dwtype)
{
struct Lws_client_connect_info tconnectinfo;
memset (&tconnectinfo, 0, sizeof (tconnectinfo));
Tconnectinfo.context = S_ptcontext;
tconnectinfo.address = "172.22.3.25";
Tconnectinfo.port = 90;
Tconnectinfo.path = Url.c_str ();
Tconnectinfo.protocol = protocols->name;
Tconnectinfo.host = "172.22.3.25";


Char *pchsession = new Char[session_len];
if (pchsession)
// {
memset (pchsession, 0, Session_len);
memcpy (Pchsession, Combineipandport (strServerIP, Wport, dwtype). C_str (), Session_len);
// }
Tconnectinfo.userdata = pchsession;

Lws_client_connect_via_info (&tconnectinfo);
}


Thread functions
DWORD WINAPI lws_servicethread (LPVOID lpparameter)
{
S_ptcontext = Createcontext ();


while (TRUE)
{
Lws_service (S_ptcontext, 50);
if (false) {
Break
}
}

Lws_context_destroy (S_ptcontext);
return 0;
}


int initlibwebsocket (string url) {

HANDLE hthread = CreateThread (0, 0, Lws_servicethread, (LPVOID), create_suspended, 0);
ResumeThread (Hthread);
Sleep (3000);

String iptemp = "127.0.0.1";
Connect (URL, iptemp, 80, 0);

return 0;
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.