<一>: 背景
19年中旬做的一个嵌入式项目, 应用层需要有一个心跳的功能, 当时决定用websocket协议, 所以当时就研究了下libwebsockets的使用. 网上的资料并不多, 当时只能研究开源库提供的测试代码, 然后改改后就合并到项目里了. 这几天又把libwebsockets重新编译了下, 顺手重新写了一个简单的websocket客户端. 主要包含了以下三个功能:
1): 定时发送心跳数据;
2): 掉网重连;
3): 是否使用ssl;
代码如<二>, 不足支持请多指教.
<二>: 代码
WebsocketClient.h如下:
#ifndef WEBSOCKET_CLIENT_H
#define WEBSOCKET_CLIENT_H
#include
#include
#define _THIS_ "this"
#define _ADDR_ "addr"
#define _PORT_ "port"
#define _PATH_ "path"
#define _SSL_ "ssl"
class WebsocketClient;
typedef struct ClientData {
struct lws_context *context;
struct lws_vhost *vhost;
struct lws *client_wsi;
const char **addr;
int *port;
const char **path;
int *ssl;
WebsocketClient *wsc;
}_ClientData;
class WebsocketClient
{
public:
WebsocketClient();
~WebsocketClient()
{
if (mContext != NULL)
{
lws_context_destroy(mContext);
mCOntext= NULL;
}
}
public:
bool Start(int argc, const char **argv);
private:
bool init(int argc, const char **argv);
public:
char msg[1024];
private:
struct lws_context *mContext;
struct lws_protocol_vhost_options lpvoAddr; // 地址
struct lws_protocol_vhost_options lpvoPort; // 端口
struct lws_protocol_vhost_options lpvoPath; // 路径
struct lws_protocol_vhost_options lpvoSSL; // 是否使用ssl
struct lws_protocol_vhost_options lpvoThis; // 传递的本类
struct lws_protocol_vhost_options lpvo;
};
#endif // WEBSOCKET_CLIENT_H
WebsocketClient.cpp如下:
#include "WebsocketClient.h"
static const char *addr = "localhost", *path = "/";
static int port = 7681, ssl = 0;
static int callBackFunc(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len);
#define WEBSOCKET_CLIENT
{
"websocket-client",
callBackFunc,
0,
1024,
0, NULL, 0
}
static struct lws_protocols lProtocols[] = {WEBSOCKET_CLIENT,{ NULL, NULL, 0, 0 }};
// 用于事件回调
static void scheduleCallBack(struct lws *wsi, int reason, int secs)
{
lws_timed_callback_vh_protocol(lws_get_vhost(wsi), lws_get_protocol(wsi), reason, secs);
}
// 连接服务
static int connectServer(_ClientData *ClientData)
{
struct lws_client_connect_info lccInfo;
memset(&lccInfo, 0, sizeof(lccInfo));
char host[32];
lws_snprintf(host, sizeof(host), "%s:%u", *ClientData->addr, *ClientData->port);
lccInfo.cOntext= ClientData->context;
lccInfo.port = *ClientData->port;
lccInfo.address = *ClientData->addr;
lccInfo.path = *ClientData->path;
lccInfo.host = host;
lccInfo.origin = host;
lccInfo.ssl_cOnnection= *ClientData->ssl;
lccInfo.vhost = ClientData->vhost;
lccInfo.pwsi = &ClientData->client_wsi;
lwsl_user("connecting to ws://%s:%d%sn", lccInfo.address, lccInfo.port, lccInfo.path);
return !lws_client_connect_via_info(&lccInfo);
}
// lws_service回调
static int callBackFunc(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len)
{
_ClientData *clientData = (_ClientData *)lws_protocol_vh_priv_get(lws_get_vhost(wsi), lws_get_protocol(wsi));
switch (reason)
{
case LWS_CALLBACK_PROTOCOL_INIT:
lwsl_user("LWS_CALLBACK_PROTOCOL_INITn");
clientData = (_ClientData *)lws_protocol_vh_priv_zalloc(lws_get_vhost(wsi), lws_get_protocol(wsi), sizeof(_ClientData));
if (!clientData)
return -1;
clientData->cOntext= lws_get_context(wsi);
clientData->vhost = lws_get_vhost(wsi);
clientData->port = (int *)lws_pvo_search((const struct lws_protocol_vhost_options *)in, _PORT_)->value;
clientData->addr = (const char **)lws_pvo_search((const struct lws_protocol_vhost_options *)in, _ADDR_)->value;
clientData->path = (const char **)lws_pvo_search((const struct lws_protocol_vhost_options *)in, _PATH_)->value;
clientData->ssl = (int *)lws_pvo_search((const struct lws_protocol_vhost_options *)in, _SSL_)->value;
char **pptr;
pptr = (char **)lws_pvo_search((const struct lws_protocol_vhost_options *)in, _THIS_)->value;
clientData->wsc = reinterpret_cast(*pptr);
if (connectServer(clientData))
scheduleCallBack(wsi, LWS_CALLBACK_USER, 1);
break;
// 连接创建成功事件, 会调用: LWS_CALLBACK_TIMER
case LWS_CALLBACK_CLIENT_ESTABLISHED:
lwsl_user("LWS_CALLBACK_CLIENT_ESTABLISHEDn");
lws_set_timer_usecs(wsi, 5 * LWS_USEC_PER_SEC);
break;
// 写事件
case LWS_CALLBACK_CLIENT_WRITEABLE:
char *tmp;
int sendLen, retLen;
tmp = (char *)"{"ping":1,"msg":"ping msg"}";
sendLen = strlen(tmp);
char sendMsg[LWS_PRE + sendLen];
memcpy(sendMsg + LWS_PRE, tmp, sendLen);
retLen = lws_write(wsi, ((unsigned char *)sendMsg) + LWS_PRE, sendLen, LWS_WRITE_TEXT);
if (retLen wsc->msg, (char *)in, len);
lwsl_user("clientData->wsc->msg: %sn", clientData->wsc->msg);
break;
// 连接错误事件, 会调用: LWS_CALLBACK_USER
case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
lwsl_err("CLIENT_CONNECTION_ERRORn");
scheduleCallBack(wsi, LWS_CALLBACK_USER, 1);
break;
// 时间事件, 会调用: LWS_CALLBACK_CLIENT_WRITEABLE
case LWS_CALLBACK_TIMER:
lws_callback_on_writable(wsi);
lws_set_timer_usecs(wsi, 5 * LWS_USEC_PER_SEC);
break;
// 客户端session关闭事件
case LWS_CALLBACK_CLIENT_CLOSED:
lwsl_user("LWS_CALLBACK_CLIENT_CLOSEDn");
lws_cancel_service(lws_get_context(wsi));
scheduleCallBack(wsi, LWS_CALLBACK_USER, 1);
break;
// 自定义事件, 当前用于重连
case LWS_CALLBACK_USER:
lwsl_notice("%s: LWS_CALLBACK_USERn", __func__);
if (connectServer(clientData))
scheduleCallBack(wsi, LWS_CALLBACK_USER, 1);
break;
default:
break;
}
return 0;
}
WebsocketClient::WebsocketClient()
{
memset(msg, 0x00, sizeof(msg));
lpvoAddr = {NULL, NULL, _ADDR_, (char *)((void *)&addr)};
lpvoPort = {&lpvoAddr, NULL, _PORT_, (char *)((void *)&port)};
lpvoPath = {&lpvoPort, NULL, _PATH_, (char *)((void *)&path)};
lpvoSSL = {&lpvoPath, NULL, _SSL_, (char *)((void *)&ssl)};
char *tmp = reinterpret_cast(this);
lpvoThis = {&lpvoSSL, NULL, _THIS_, (char *)((void *)(&tmp))};
lpvo = {NULL, &lpvoThis, "websocket-client", ""};
}
bool WebsocketClient::init(int argc, const char **argv)
{
struct lws_context_creation_info lcrInfo;
memset(&lcrInfo, 0, sizeof lcrInfo);
const char *tmpPtr = NULL;
int logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE;
// 连接地址
if ((tmpPtr = lws_cmdline_option(argc, argv, "--addr")))
addr = tmpPtr;
// 连接端口
if ((tmpPtr = lws_cmdline_option(argc, argv, "--port")))
port = atoi(tmpPtr);
// 虚拟路径
if ((tmpPtr = lws_cmdline_option(argc, argv, "--path")))
path = tmpPtr;
// 是否使用ssl
if ((tmpPtr = lws_cmdline_option(argc, argv, "--ssl")))
ssl = atoi(tmpPtr);
if (ssl)
{
if ((tmpPtr = lws_cmdline_option(argc, argv, "--ca_path")))
{
lcrInfo.client_ssl_ca_filepath = tmpPtr;
}
else
{
lwsl_err("cannot find ca_pathn");
return false;
}
}
// 日志输出等级
if ((tmpPtr = lws_cmdline_option(argc, argv, "--log_level")))
logs = atoi(tmpPtr);
lws_set_log_level(logs, NULL);
lcrInfo.port = CONTEXT_PORT_NO_LISTEN; /* we do not run any server */
lcrInfo.protocols = lProtocols;
lcrInfo.pvo = &lpvo;
lcrInfo.pt_serv_buf_size = 32 * 1024;
lcrInfo.optiOns= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT | LWS_SERVER_OPTION_VALIDATE_UTF8;
lcrInfo.fd_limit_per_thread = 1 + 1 + 1;
mCOntext= lws_create_context(&lcrInfo);
if (!mContext)
{
lwsl_err("lws init failedn");
return false;
}
return true;
}
bool WebsocketClient::Start(int argc, const char **argv)
{
if (!init(argc, argv))
{
return false;
}
while (!lws_service(mContext, 0));
lws_context_destroy(mContext);
return true;
}
测试文件main.cpp如下:
#include "WebsocketClient.h"
int main(int argc, const char **argv)
{
WebsocketClient websocketClient;
if (!websocketClient.Start(argc, argv))
{
return -1;
}
return 0;
}
编译命令如下:
g++ main.cpp WebsocketClient.cpp -o main -lwebsockets -Wall -std=c++11
<三>: 测试
打开一个websocket服务, 如果没有, 可以根据上篇文章编译一个echo服务. 本测试就用自己编译的echo服务, 结果如下:
结束:
如果有什么问题, 大家可以一起讨论解决.