一个简单小巧易用稳定高效的http网络库

xingyun86 2022-7-16 1112

一个简单小巧易用稳定高效的http网络库

v1.1更新:

新增了http和https的服务端和客户端同步异步请求接口API

新增websocket ws和wss的客服端及服务端接口API

支持自定义证书端口和服务名称,遵循websocket rfc协议


特点:

支持win32api的http/https 同步或异步请求

支持win32api的http/https自动识别(兼容http 1.0/1.1/2.0)

支持UTF8和ANSI及UNICODE之间编码转换

支持windows xp-windows 11

支持隐式或者显示调用

接口说明如下:

#pragma once
#ifdef PLYAPIDLL_EXPORTS
#define PLYAPIDLL_API __declspec(dllexport)
#else
#define PLYAPIDLL_API __declspec(dllimport)
#endif // PLYAPIDLL_EXPORTS
class PLYAPIDLL_API CPlyApi
{
public:
};
typedef enum HttpStepType {
	HSTYPE_CrackUrl = 0,
	HSTYPE_Open,
	HSTYPE_Connect,
	HSTYPE_OpenRequest,
	HSTYPE_AddRequestHeaders,
	HSTYPE_SendRequest,
	HSTYPE_ReceiveResponse,
	HSTYPE_QueryRawHeaders,
	HSTYPE_QueryDataAvailable,
	HSTYPE_ReadData,
	HSTYPE_LeaveClean,
} HttpStepType;
typedef int (*PFN_WindowsCallBack)(HttpStepType httpStepType, DWORD dwErrorId, LPVOID hSession, LPVOID hConnect, LPVOID hRequest, LPVOID lpData, UINT uSize, BOOL *pbResponseHeadersOnly, LPVOID lpUserData);
PLYAPIDLL_API int PlyHttpExecAsync(LPCWSTR lpMethod, PFN_WindowsCallBack pfnUserFunc, LPVOID lpUserData, LPCWSTR lpwUrl, LPCWSTR lpwRequestHeaders = L"Accept:*/*\r\n", LPCSTR lpRequestData = NULL/*WINHTTP_NO_REQUEST_DATA*/, LPCWSTR lpwUserAgent = L"PLYAPI/1.0");
PLYAPIDLL_API int PlyHttpGetAsync(PFN_WindowsCallBack pfnUserFunc, LPVOID lpUserData, LPCWSTR lpwUrl, LPCWSTR lpwRequestHeaders = L"Accept:*/*\r\n", LPCSTR lpRequestData = NULL/*WINHTTP_NO_REQUEST_DATA*/, LPCWSTR lpwUserAgent = L"PLYAPI/1.0");
PLYAPIDLL_API int PlyHttpPostAsync(PFN_WindowsCallBack pfnUserFunc, LPVOID lpUserData, LPCWSTR lpwUrl, LPCWSTR lpwRequestHeaders = L"Accept:*/*\r\n", LPCSTR lpRequestData = NULL/*WINHTTP_NO_REQUEST_DATA*/, LPCWSTR lpwUserAgent = L"PLYAPI/1.0");
PLYAPIDLL_API int PlyHttpExec(LPCWSTR lpMethod, PFN_WindowsCallBack pfnUserFunc, LPVOID lpUserData, LPCWSTR lpwUrl, LPCWSTR lpwRequestHeaders = L"Accept:*/*\r\n", LPCSTR lpRequestData = NULL/*WINHTTP_NO_REQUEST_DATA*/, LPCWSTR lpwUserAgent = L"PLYAPI/1.0");
PLYAPIDLL_API int PlyHttpGet(PFN_WindowsCallBack pfnUserFunc, LPVOID lpUserData, LPCWSTR lpwUrl, LPCWSTR lpwRequestHeaders = L"Accept:*/*\r\n", LPCSTR lpRequestData = NULL/*WINHTTP_NO_REQUEST_DATA*/, LPCWSTR lpwUserAgent = L"PLYAPI/1.0");
PLYAPIDLL_API int PlyHttpPost(PFN_WindowsCallBack pfnUserFunc, LPVOID lpUserData, LPCWSTR lpwUrl, LPCWSTR lpwRequestHeaders = L"Accept:*/*\r\n", LPCSTR lpRequestData = NULL/*WINHTTP_NO_REQUEST_DATA*/, LPCWSTR lpwUserAgent = L"PLYAPI/1.0");
PLYAPIDLL_API int PlyMToW(WCHAR* w, INT ws, const CHAR* m, const INT ms, UINT cp);
PLYAPIDLL_API int PlyWToM(CHAR* m, INT ms, const WCHAR* w, const INT ws, UINT cp);
PLYAPIDLL_API int PlyUTF8ToW(WCHAR* w, INT ws, const CHAR* u, const INT us);
PLYAPIDLL_API int PlyWToUTF8(CHAR* u, INT us, const WCHAR* w, const INT ws);
PLYAPIDLL_API int PlyAToW(WCHAR* w, INT ws, const CHAR* a, const INT as);
PLYAPIDLL_API int PlyWToA(CHAR* a, INT as, const WCHAR* w, const INT ws);
#pragma pack(push,1)
typedef struct PlyCallBackData {
    void* pInstance;
    void* pUserData;
    bool bSecureSSL;
}PlyCallBackData;
#pragma pack(pop)
typedef void (*PFN_WebSocketOnMessage)(void* pConn, const char* pMsg, unsigned int nMsgSize, void* pCallBackData);
typedef void (*PFN_WebSocketOnOpen)(void* pConn, void* pCallBackData);
typedef void (*PFN_WebSocketOnClose)(void* pConn, int nStatus, const char* pReasonDesc, void* pCallBackData);
typedef void (*PFN_WebSocketOnError)(void* pConn, int nErrorCode, const char* pErrorDesc, void* pCallBackData);
typedef void (*PFN_WebSocketOnPing)(void* pConn, void* pCallBackData);
typedef void (*PFN_WebSocketOnPong)(void* pConn, void* pCallBackData);
typedef void (*PFN_WebSocketOnSendError)(int nErrorCode, const char* pErrorDesc, void* pCallBackData);
PLYAPIDLL_API void* PlyWebsocketServerCreate(bool bWSS, unsigned short nPort, 
	const char* pCertFile = "", const char* pPrivateKeyFile = "", const char* pVerifyFile = "");
PLYAPIDLL_API void PlyWebsocketServerInit(bool bWSS, void* pWebsocketServer,
    PFN_WebSocketOnMessage onMessage = 0L, PFN_WebSocketOnOpen onOpen = 0L, PFN_WebSocketOnClose onClose = 0L, PFN_WebSocketOnError onError = 0L,
    PFN_WebSocketOnPing onPing = 0L, PFN_WebSocketOnPong onPong = 0L, PFN_WebSocketOnSendError onSendError = 0L, const char* pName = "echo", void* pUserData = 0L);
PLYAPIDLL_API void PlyWebsocketServerConnSend(bool bWSS, void* pWebsocketServer, void* pConn, const char* pMsg, unsigned int nMsgSize);
PLYAPIDLL_API void PlyWebsocketServerConnSendClose(bool bWSS, void* pWebsocketServer, void* pConn, int nStatus, const char* pReason);
PLYAPIDLL_API void PlyWebsocketServerStart(bool bWSS, void* pWebsocketServer);
PLYAPIDLL_API void PlyWebsocketServerStop(bool bWSS, void* pWebsocketServer);
PLYAPIDLL_API void PlyWebsocketServerDestroy(bool bWSS, void** ppWebsocketServer);
PLYAPIDLL_API void* PlyWebsocketClientCreate(bool bWSS, 
    const char* pUrl = 0L, bool bVerifyCertificate = true, const char* pCertFile = "", 
	const char* pPrivateKeyFile = "", const char* pVerifyFile = "", unsigned short nDefaultPort = 0);
PLYAPIDLL_API void PlyWebsocketClientInit(bool bWSS, void* pWebsocketClient,
    PFN_WebSocketOnMessage onMessage = 0L, PFN_WebSocketOnOpen onOpen = 0L, PFN_WebSocketOnClose onClose = 0L, PFN_WebSocketOnError onError = 0L,
    PFN_WebSocketOnPing onPing = 0L, PFN_WebSocketOnPong onPong = 0L, PFN_WebSocketOnSendError onSendError = 0L, void* pUserData = 0L);
PLYAPIDLL_API void PlyWebsocketClientSend(bool bWSS, void* pWebsocketClient, const char* pMsg, unsigned int nMsgSize);
PLYAPIDLL_API void PlyWebsocketClientSendClose(bool bWSS, void* pWebsocketClient, int nStatus, const char* pReason);
PLYAPIDLL_API void PlyWebsocketClientConnSend(bool bWSS, void* pWebsocketClient, void* pConn, const char* pMsg, unsigned int nMsgSize);
PLYAPIDLL_API void PlyWebsocketClientConnSendClose(bool bWSS, void* pWebsocketClient, void* pConn, int nStatus, const char* pReason);
PLYAPIDLL_API void PlyWebsocketClientStart(bool bWSS, void* pWebsocketClient);
PLYAPIDLL_API void PlyWebsocketClientStop(bool bWSS, void* pWebsocketClient);
PLYAPIDLL_API void PlyWebsocketClientDestroy(bool bWSS, void** ppWebsocketClient);
typedef void (*PFN_HttpOnHandler)(void* pRequest, void* pResponse, void* pCallBackData);
typedef void (*PFN_HttpOnError)(void* pResponse, int nErrorCode, const char* pErrorDesc, void* pCallBackData);
typedef void (*PFN_HttpOnSendError)(int nErrorCode, const char* pErrorDesc, void* pCallBackData);
typedef void (*PFN_HttpGetValue)(int nIndex, const char* pValue, unsigned int nValueSize, void* pUserData);
typedef void (*PFN_HttpGetKeyValue)(int index, const char* pKey, unsigned int nKeySize, const char* pValue, unsigned int nValueSize, void* pUserData);
PLYAPIDLL_API int PlyHttpServerReqGetPath(bool bHTTPS, void* pRequest, PFN_HttpGetValue httpGetValue, void* pUserData);
PLYAPIDLL_API int PlyHttpServerReqGetMethod(bool bHTTPS, void* pRequest, PFN_HttpGetValue httpGetValue, void* pUserData);
PLYAPIDLL_API int PlyHttpServerReqGetContent(bool bHTTPS, void* pRequest, PFN_HttpGetValue httpGetValue, void* pUserData);
PLYAPIDLL_API int PlyHttpServerReqGetHttpVersion(bool bHTTPS, void* pRequest, PFN_HttpGetValue httpGetValue, void* pUserData);
PLYAPIDLL_API int PlyHttpServerReqGetQueryString(bool bHTTPS, void* pRequest, PFN_HttpGetValue httpGetValue, void* pUserData);
PLYAPIDLL_API int PlyHttpServerReqGetPathMatchCount(bool bHTTPS, void* pRequest);
PLYAPIDLL_API int PlyHttpServerReqGetPathMatchIndex(bool bHTTPS, void* pRequest, int nIndex, PFN_HttpGetValue httpGetValue, void* pUserData);
PLYAPIDLL_API int PlyHttpServerReqGetHeaderCount(bool bHTTPS, void* pRequest);
PLYAPIDLL_API int PlyHttpServerReqGetHeaderIndex(bool bHTTPS, void* pRequest, int nIndex, PFN_HttpGetKeyValue httpGetKeyValue, void* pUserData);
PLYAPIDLL_API int PlyHttpServerReqGetQueryStringCount(bool bHTTPS, void* pRequest);
PLYAPIDLL_API int PlyHttpServerReqGetQueryStringIndex(bool bHTTPS, void* pRequest, int nIndex, PFN_HttpGetKeyValue httpGetKeyValue, void* pUserData);
PLYAPIDLL_API int PlyHttpClientRespGetContent(bool bHTTPS, void* pResponse, PFN_HttpGetValue httpGetValue, void* pUserData);
PLYAPIDLL_API int PlyHttpClientRespGetStatusCode(bool bHTTPS, void* pResponse, PFN_HttpGetValue httpGetValue, void* pUserData);
PLYAPIDLL_API int PlyHttpClientRespGetHttpVersion(bool bHTTPS, void* pResponse, PFN_HttpGetValue httpGetValue, void* pUserData);
PLYAPIDLL_API int PlyHttpClientRespGetHeaderCount(bool bHTTPS, void* pResponse);
PLYAPIDLL_API int PlyHttpClientRespGetHeaderIndex(bool bHTTPS, void* pResponse, int nIndex, PFN_HttpGetKeyValue httpGetKeyValue, void* pUserData);
PLYAPIDLL_API void* PlyHttpServerCreate(bool bHTTPS, unsigned short nPort, const char* pCertFile = 0L, const char* pPrivateKeyFile = 0L, const char* pVerifyFile = 0L);
PLYAPIDLL_API void PlyHttpServerInit(bool bHTTPS, void* pHttpServer, PFN_HttpOnError onMessage = 0L, const char* pRootPath = "web", void* pUserData = 0L);
PLYAPIDLL_API void PlyHttpServerAddService(bool bHTTPS, void* pHttpServer, const char* pServiceName = "", const char* pServiceMethod = "GET", PFN_HttpOnHandler onHandler = 0L);
PLYAPIDLL_API void PlyHttpServerConnSend(bool bHTTPS, void* pHttpServer, void* pConn, const char* pMsg, unsigned int nMsgSize, bool bCloseConnectionAfterResponse = true);
PLYAPIDLL_API void PlyHttpServerStart(bool bHTTPS, void* pHttpServer);
PLYAPIDLL_API void PlyHttpServerStop(bool bHTTPS, void* pHttpServer);
PLYAPIDLL_API void PlyHttpServerDestroy(bool bHTTPS, void** ppHttpServer);
PLYAPIDLL_API void* PlyHttpClientCreate(bool bHTTPS, const char * pServerPortPath, bool bVerifyCertificate = false, const char* pCertFile = 0L, const char* pPrivateKey_file = 0L, const char* pVerifyFile = 0L, unsigned short nDefaultPort = 80);
PLYAPIDLL_API void PlyHttpClientInit(bool bHTTPS, void* pHttpServer, void* pUserData = 0L);
PLYAPIDLL_API void PlyHttpClientSendSync(bool bHTTPS, void* pHttpClient, const char* pMethod, const char* pUri, const char* pMsg, unsigned int nMsgSize, const char* pHeaders, PFN_HttpOnHandler onHandler, PFN_HttpOnSendError onSendError);
PLYAPIDLL_API void PlyHttpClientSendAsync(bool bHTTPS, void* pHttpClient, const char* pMethod, const char* pUri, const char* pMsg, unsigned int nMsgSize, const char* pHeaders, PFN_HttpOnHandler onHandler, PFN_HttpOnSendError onSendError);
PLYAPIDLL_API void PlyHttpClientStart(bool bHTTPS, void* pHttpServer);
PLYAPIDLL_API void PlyHttpClientStop(bool bHTTPS, void* pHttpServer);
PLYAPIDLL_API void PlyHttpClientDestroy(bool bHTTPS, void** ppHttpServer);

扩展使用之添加代理访问:

    std::string strRespData = "";
    PlyHttpGet([](HttpStepType httpStepType, DWORD dwErrorId,
        LPVOID hSession, LPVOID hConnect, LPVOID hRequest, 
        LPVOID lpData, UINT uSize, BOOL* pbResponseHeadersOnly, LPVOID lpUserData)->int
        {
            switch (httpStepType)
            {
            case HSTYPE_CrackUrl:
                break;
            case HSTYPE_Open:
            {
                WINHTTP_PROXY_INFO proxy = { 0 };
                proxy.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
                proxy.lpszProxy = (LPWSTR)L"http://127.0.0.1:1234;http://ccc.com:8088";
                if (!::WinHttpSetOption(hSession, WINHTTP_OPTION_PROXY, &proxy, sizeof(proxy)))
                {
                    printf("Unable to set proxy.\n");
                }
            }
                break;
            case HSTYPE_Connect:
                break;
            case HSTYPE_OpenRequest:
                break;
            case HSTYPE_SendRequest:
                break;
            case HSTYPE_ReceiveResponse:
                break;
            case HSTYPE_QueryRawHeaders:
                break;
            case HSTYPE_QueryDataAvailable:
                break;
            case HSTYPE_ReadData:
                //fwrite(pData, uSize, 1, (FILE*)lpUserData);
                ((std::string*)lpUserData)->append((CHAR*)lpData, uSize);
                break;
            case HSTYPE_LeaveClean:
                break;
            default:
                break;
            }
            return 0;
        }, &strRespData,
        L"https://cn.bing.com"
        );
    printf("%s\n", strRespData.c_str());

扩展使用之添加超时限制:

class MyApi {
public:
    std::wstring wstrUrl = L"";
    std::wstring wstrUserAgent = L"";
    std::wstring wstrRequestHeaders = L"";
    std::wstring wstrRequestData = L"";
public:
    std::string strResponseData = "";
    std::wstring wstrResponseHeaders = L"";
};
MyApi myApi;
myApi.wstrUrl = L"https://cn.bing.com";
myApi.wstrUserAgent = L"PLYAPI/1.0";
myApi.wstrRequestHeaders = L"Accept: */*\r\n";
PlyHttpGet([](HttpStepType httpStepType, DWORD dwErrorId,
    LPVOID hSession, LPVOID hConnect, LPVOID hRequest, 
    LPVOID lpData, UINT uSize, BOOL* pbResponseHeadersOnly, LPVOID lpUserData)->int
    {
        switch (httpStepType)
        {
        case HSTYPE_CrackUrl:
            break;
        case HSTYPE_Open:
        {
            ::WinHttpSetTimeouts(hSession, 20000, 20000, 0, 0);
        }
            break;
        case HSTYPE_Connect:
            break;
        case HSTYPE_OpenRequest:
            break;
        case HSTYPE_SendRequest:
            break;
        case HSTYPE_ReceiveResponse:
            break;
        case HSTYPE_QueryRawHeaders:
            ((MyApi*)lpUserData)->wstrResponseHeaders.append((WCHAR*)lpData, uSize);
            break;
        case HSTYPE_QueryDataAvailable:
            break;
        case HSTYPE_ReadData:
            ((MyApi*)lpUserData)->strResponseData.append((CHAR*)lpData, uSize);
            break;
        case HSTYPE_LeaveClean:
            break;
        default:
            break;
        }
        return 0;
    }, &myApi, myApi.wstrUrl.c_str(),myApi.wstrRequestHeaders.c_str(), NULL, myApi.wstrUserAgent.c_str());
printf("%ws\n", myApi.wstrRequestHeaders.c_str());
printf("%s\n", myApi.strResponseData.c_str());

扩展使用之只获取返回头部信息:

class MyApi {
public:
    std::wstring wstrUrl = L"";
    std::wstring wstrUserAgent = L"";
    std::wstring wstrRequestHeaders = L"";
    std::wstring wstrRequestData = L"";
public:
    std::string strResponseData = "";
    std::wstring wstrResponseHeaders = L"";
};
MyApi myApi;
myApi.wstrUrl = L"https://cn.bing.com";
myApi.wstrUserAgent = L"PLYAPI/1.0";
myApi.wstrRequestHeaders = L"Accept: */*\r\n";
PlyHttpGet([](HttpStepType httpStepType, DWORD dwErrorId,
    LPVOID hSession, LPVOID hConnect, LPVOID hRequest, 
    LPVOID lpData, UINT uSize, BOOL* pbResponseHeadersOnly, LPVOID lpUserData)->int
    {
        switch (httpStepType)
        {
        case HSTYPE_CrackUrl:
            break;
        case HSTYPE_Open:
            break;
        case HSTYPE_Connect:
            break;
        case HSTYPE_OpenRequest:
            break;
        case HSTYPE_SendRequest:
            break;
        case HSTYPE_ReceiveResponse:
            break;
        case HSTYPE_QueryRawHeaders:
            (*pbResponseHeadersOnly) = TRUE;
            ((MyApi*)lpUserData)->wstrResponseHeaders.append((WCHAR*)lpData, uSize);
            break;
        case HSTYPE_QueryDataAvailable:
            break;
        case HSTYPE_ReadData:
            //((MyApi*)lpUserData)->strResponseData.append((CHAR*)lpData, uSize);
            break;
        case HSTYPE_LeaveClean:
            break;
        default:
            break;
        }
        return 0;
    }, &myApi, myApi.wstrUrl.c_str(),myApi.wstrRequestHeaders.c_str(), NULL, myApi.wstrUserAgent.c_str());
printf("%ws\n", myApi.wstrRequestHeaders.c_str());
printf("%s\n", myApi.strResponseData.c_str());

扩展使用之修改HTTP请求协议版本:

class MyApi {
public:
    std::wstring wstrUrl = L"";
    std::wstring wstrUserAgent = L"";
    std::wstring wstrRequestHeaders = L"";
    std::wstring wstrRequestData = L"";
public:
    std::string strResponseData = "";
    std::wstring wstrResponseHeaders = L"";
};
MyApi myApi;
myApi.wstrUrl = L"https://cn.bing.com";
myApi.wstrUserAgent = L"PLYAPI/1.0";
myApi.wstrRequestHeaders = L"Accept: */*\r\n";
PlyHttpGet([](HttpStepType httpStepType, DWORD dwErrorId,
    LPVOID hSession, LPVOID hConnect, LPVOID hRequest, 
    LPVOID lpData, UINT uSize, BOOL* pbResponseHeadersOnly, LPVOID lpUserData)->int
    {
        switch (httpStepType)
        {
        case HSTYPE_CrackUrl:
            break;
        case HSTYPE_Open:
        {
            HTTP_VERSION_INFO version;
            version.dwMajorVersion = 1;
            version.dwMinorVersion = 1;
            ::WinHttpSetOption(hSession, WINHTTP_OPTION_HTTP_VERSION, &version, sizeof(version));
        }
            break;
        case HSTYPE_Connect:
            break;
        case HSTYPE_OpenRequest:
            break;
        case HSTYPE_SendRequest:
            break;
        case HSTYPE_ReceiveResponse:
            break;
        case HSTYPE_QueryRawHeaders:
            (*pbResponseHeadersOnly) = TRUE;
            ((MyApi*)lpUserData)->wstrResponseHeaders.append((WCHAR*)lpData, uSize);
            break;
        case HSTYPE_QueryDataAvailable:
            break;
        case HSTYPE_ReadData:
            //((MyApi*)lpUserData)->strResponseData.append((CHAR*)lpData, uSize);
            break;
        case HSTYPE_LeaveClean:
            break;
        default:
            break;
        }
        return 0;
    }, &myApi, myApi.wstrUrl.c_str(),myApi.wstrRequestHeaders.c_str(), NULL, myApi.wstrUserAgent.c_str());
printf("%ws\n", myApi.wstrRequestHeaders.c_str());
printf("%s\n", myApi.strResponseData.c_str());

扩展使用之禁止重定向:

class MyApi {
public:
    std::wstring wstrUrl = L"";
    std::wstring wstrUserAgent = L"";
    std::wstring wstrRequestHeaders = L"";
    std::wstring wstrRequestData = L"";
public:
    std::string strResponseData = "";
    std::wstring wstrResponseHeaders = L"";
};
MyApi myApi;
myApi.wstrUrl = L"https://cn.bing.com";
myApi.wstrUserAgent = L"PLYAPI/1.0";
myApi.wstrRequestHeaders = L"Accept: */*\r\n";
PlyHttpGet([](HttpStepType httpStepType, DWORD dwErrorId,
    LPVOID hSession, LPVOID hConnect, LPVOID hRequest, 
    LPVOID lpData, UINT uSize, BOOL* pbResponseHeadersOnly, LPVOID lpUserData)->int
    {
        switch (httpStepType)
        {
        case HSTYPE_CrackUrl:
            break;
        case HSTYPE_Open:
        {
            ULONG disableFeture = WINHTTP_DISABLE_REDIRECTS;
            ::WinHttpSetOption(hSession, WINHTTP_OPTION_DISABLE_FEATURE, &disableFeture , sizeof(disableFeture ));
        }
            break;
        case HSTYPE_Connect:
            break;
        case HSTYPE_OpenRequest:
            break;
        case HSTYPE_SendRequest:
            break;
        case HSTYPE_ReceiveResponse:
            break;
        case HSTYPE_QueryRawHeaders:
            (*pbResponseHeadersOnly) = TRUE;
            ((MyApi*)lpUserData)->wstrResponseHeaders.append((WCHAR*)lpData, uSize);
            break;
        case HSTYPE_QueryDataAvailable:
            break;
        case HSTYPE_ReadData:
            //((MyApi*)lpUserData)->strResponseData.append((CHAR*)lpData, uSize);
            break;
        case HSTYPE_LeaveClean:
            break;
        default:
            break;
        }
        return 0;
    }, &myApi, myApi.wstrUrl.c_str(),myApi.wstrRequestHeaders.c_str(), NULL, myApi.wstrUserAgent.c_str());
printf("%ws\n", myApi.wstrRequestHeaders.c_str());
printf("%s\n", myApi.strResponseData.c_str());

websocket websockets client/server使用案例:

void test_websocket_websocket_client_server()
{
    bool bUseSsl = false;
    std::string name = "echo";
    void* pWsServer = PlyWebsocketServerCreate(bUseSsl, 8080);
    void* pWsClient = PlyWebsocketClientCreate(bUseSsl, ("localhost:8080/" + name).c_str());
    void* pWsSSLServer = PlyWebsocketServerCreate(!bUseSsl, 443, "server.crt", "server.key");
    void* pWsSSLClient = PlyWebsocketClientCreate(!bUseSsl, ("localhost:443/" + name).c_str(), false);
    if (pWsServer == NULL)
    {
        goto __LEAVE_CLEAN__;
    }
    if (pWsClient == NULL)
    {
        goto __LEAVE_CLEAN__;
    }
    if (pWsSSLServer == NULL)
    {
        goto __LEAVE_CLEAN__;
    }
    if (pWsSSLClient == NULL)
    {
        goto __LEAVE_CLEAN__;
    }
    PlyWebsocketServerInit(bUseSsl, pWsServer, [](void* pConn, const char* pMsg, unsigned int nMsgSize, void* pCallBackData) {
        PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
        std::cout << "Server: Message received:" << pMsg << std::endl;
        PlyWebsocketServerConnSend(pCBD->bSecureSSL, pCBD->pInstance, pConn, pMsg, nMsgSize);
        }, [](void* pConn, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: Opened connection " << std::endl;
        }, [](void* pConn, int nStatus, const char* pReasonDesc, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: Closed connection with status code " << nStatus << ",desc is " << pReasonDesc << std::endl;
        }, [](void* pConn, int nErrorCode, const char* pErrorDesc, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: Error: " << nErrorCode << ", error message: " << pErrorDesc << std::endl;
        }, [](void* pConn, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: onPing message" << std::endl;
        }, [](void* pConn, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: onPong message" << std::endl;
        }, [](int nErrorCode, const char* pErrorDesc, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: Error: " << nErrorCode << ", error message: " << pErrorDesc << std::endl;
        }, name.c_str(), NULL);
    PlyWebsocketServerInit(!bUseSsl, pWsSSLServer, [](void* pConn, const char* pMsg, unsigned int nMsgSize, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: Message received:" << pMsg << std::endl;
            PlyWebsocketServerConnSend(pCBD->bSecureSSL, pCBD->pInstance, pConn, pMsg, nMsgSize);
        }, [](void* pConn, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: Opened connection " << std::endl;
        }, [](void* pConn, int nStatus, const char* pReasonDesc, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: Closed connection with status code " << nStatus << ",desc is " << pReasonDesc << std::endl;
        }, [](void* pConn, int nErrorCode, const char* pErrorDesc, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: Error: " << nErrorCode << ", error message: " << pErrorDesc << std::endl;
        }, [](void* pConn, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: onPing message" << std::endl;
        }, [](void* pConn, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: onPong message" << std::endl;
        }, [](int nErrorCode, const char* pErrorDesc, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Server: Error: " << nErrorCode << ", error message: " << pErrorDesc << std::endl;
        }, name.c_str(), NULL);
    PlyWebsocketClientInit(bUseSsl, pWsClient, [](void* pConn, const char* pMsg, unsigned int nMsgSize, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Client: Message received:" << pMsg << std::endl;
        }, [](void* pConn, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            PlyWebsocketClientConnSend(pCBD->bSecureSSL, pCBD->pInstance, pConn, "Hello", strlen("Hello"));
        }, [](void* pConn, int nStatus, const char* pReasonDesc, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Client: Closed connection with status code " << nStatus << ",desc is " << pReasonDesc << std::endl;
        }, [](void* pConn, int nErrorCode, const char* pErrorDesc, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Client: Error: " << nErrorCode << ", error message: " << pErrorDesc << std::endl;
        }, [](void* pConn, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            PlyWebsocketClientConnSend(pCBD->bSecureSSL, pCBD->pInstance, pConn, "Ping", strlen("Ping"));
        }, [](void* pConn, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            PlyWebsocketClientConnSend(pCBD->bSecureSSL, pCBD->pInstance, pConn, "Pong", strlen("Pong"));
        }, [](int nErrorCode, const char* pErrorDesc, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Client: Error: " << nErrorCode << ", error message: " << pErrorDesc << std::endl;
        }, NULL);
    PlyWebsocketClientInit(!bUseSsl, pWsSSLClient, [](void* pConn, const char* pMsg, unsigned int nMsgSize, void* pCallBackData) {
        PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
        std::cout << "Client: Message received:" << pMsg << std::endl;
        }, [](void* pConn, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            PlyWebsocketClientConnSend(pCBD->bSecureSSL, pCBD->pInstance, pConn, "Hello", strlen("Hello"));
        }, [](void* pConn, int nStatus, const char* pReasonDesc, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Client: Closed connection with status code " << nStatus << ",desc is " << pReasonDesc << std::endl;
        }, [](void* pConn, int nErrorCode, const char* pErrorDesc, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Client: Error: " << nErrorCode << ", error message: " << pErrorDesc << std::endl;
        }, [](void* pConn, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            PlyWebsocketClientConnSend(pCBD->bSecureSSL, pCBD->pInstance, pConn, "Ping", strlen("Ping"));
        }, [](void* pConn, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            PlyWebsocketClientConnSend(pCBD->bSecureSSL, pCBD->pInstance, pConn, "Pong", strlen("Pong"));
        }, [](int nErrorCode, const char* pErrorDesc, void* pCallBackData) {
            PlyCallBackData* pCBD = (PlyCallBackData*)pCallBackData;
            std::cout << "Client: Error: " << nErrorCode << ", error message: " << pErrorDesc << std::endl;
        }, NULL);
    {
        std::thread([bUseSsl, pWsServer]() { PlyWebsocketServerStart(bUseSsl, pWsServer); }).detach();
        std::thread([bUseSsl, pWsSSLServer]() { PlyWebsocketServerStart(!bUseSsl, pWsSSLServer); }).detach();
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::thread([bUseSsl, pWsClient]() { PlyWebsocketClientStart(bUseSsl, pWsClient); }).detach();
        std::thread([bUseSsl, pWsSSLClient]() { PlyWebsocketClientStart(!bUseSsl, pWsSSLClient); }).detach();
        int i = 0;
        while (true)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
            auto msg = ("ws ok!" + std::to_string(i++));
            PlyWebsocketClientSend(bUseSsl, pWsClient, msg.c_str(), msg.length());
            msg = ("wss ok!" + std::to_string(i++));
            PlyWebsocketClientSend(!bUseSsl, pWsSSLClient, msg.c_str(), msg.length());
        }
    }
__LEAVE_CLEAN__:
    if (pWsServer != NULL)
    {
        PlyWebsocketServerDestroy(bUseSsl, &pWsServer);
    }
    if (pWsClient != NULL)
    {
        PlyWebsocketClientDestroy(bUseSsl, &pWsClient);
    }
    if (pWsSSLServer != NULL)
    {
        PlyWebsocketServerDestroy(!bUseSsl, &pWsServer);
    }
    if (pWsSSLClient != NULL)
    {
        PlyWebsocketClientDestroy(!bUseSsl, &pWsClient);
    }
}
http/https client/server使用案例:
void test_http_https_client_server()
{
    class StringContent {
    public:
        std::string content = std::string();
    };
    bool bUseSsl = false;
    void* pHttpServer = PlyHttpServerCreate(bUseSsl, 8080);
    void* pHttpClient = PlyHttpClientCreate(bUseSsl, "localhost:8080");
    void* pHttpSSLServer = PlyHttpServerCreate(!bUseSsl, 1443, "server.crt", "server.key");
    void* pHttpSSLClient = PlyHttpClientCreate(!bUseSsl, "localhost:1443", false);
    if (pHttpServer == NULL)
    {
        goto __LEAVE_CLEAN__;
    }
    if (pHttpClient == NULL)
    {
        goto __LEAVE_CLEAN__;
    }
    if (pHttpSSLServer == NULL)
    {
        goto __LEAVE_CLEAN__;
    }
    if (pHttpSSLClient == NULL)
    {
        goto __LEAVE_CLEAN__;
    }
    PlyHttpServerAddService(bUseSsl, pHttpServer, "/string", "POST", [](void* pRequest, void* pResponse, void* pCallBackData)
        {
            PlyCallBackData* pcbd = (PlyCallBackData*)pCallBackData;
            class ReqContent {
            public:
                std::string content = std::string();
            } reqContent;
            PlyHttpServerReqGetContent(pcbd->bSecureSSL, pRequest, [](int nIndex, const char* pValue, unsigned int nValueSize, void* pUserData) 
                {
                    ReqContent* pReqContent = (ReqContent*)pUserData;
                    pReqContent->content.assign(pValue, nValueSize);
                }, & reqContent);
            std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: " + std::to_string(reqContent.content.length()) + "\r\n\r\n" + reqContent.content;
            PlyHttpServerConnSend(pcbd->bSecureSSL, pcbd->pInstance, pResponse, resp.data(), resp.length(), false);
        });
    PlyHttpServerAddService(bUseSsl, pHttpServer, "/mymatch/([0-9]+)", "GET", [](void* pRequest, void* pResponse, void* pCallBackData)
        {
            PlyCallBackData* pcbd = (PlyCallBackData*)pCallBackData;
            class ReqContent {
            public:
                std::string content = std::string();
            } reqContent;
            PlyHttpServerReqGetPathMatchIndex(pcbd->bSecureSSL, pRequest, 1, [](int nIndex, const char* pValue, unsigned int nValueSize, void* pUserData)
                {
                    ReqContent* pReqContent = (ReqContent*)pUserData;
                    pReqContent->content.assign(pValue, nValueSize);
                }, &reqContent);
            std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: " + std::to_string(reqContent.content.length()) + "\r\n\r\n" + reqContent.content;
            PlyHttpServerConnSend(pcbd->bSecureSSL, pcbd->pInstance, pResponse, resp.data(), resp.length(), false);
        });
    PlyHttpServerInit(bUseSsl, pHttpServer, [](void* pConn, int nErrorCode, const char* pErrorDesc, void* pCallBackData) 
        {
        });
    PlyHttpServerAddService(!bUseSsl, pHttpSSLServer, "/string", "POST", [](void* pRequest, void* pResponse, void* pCallBackData)
        {
            PlyCallBackData* pcbd = (PlyCallBackData*)pCallBackData;
            StringContent strContent;
            PlyHttpServerReqGetContent(pcbd->bSecureSSL, pRequest, [](int nIndex, const char* pValue, unsigned int nValueSize, void* pUserData)
                {
                    auto pReqContent = (StringContent*)pUserData;
                    pReqContent->content.assign(pValue, nValueSize);
                }, & strContent);
            std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: " + std::to_string(strContent.content.length()) + "\r\n\r\n" + strContent.content;
            PlyHttpServerConnSend(pcbd->bSecureSSL, pcbd->pInstance, pResponse, resp.data(), resp.length(), false);
        });
    PlyHttpServerAddService(!bUseSsl, pHttpSSLServer, "/mymatch/([0-9]+)", "GET", [](void* pRequest, void* pResponse, void* pCallBackData)
        {
            PlyCallBackData* pcbd = (PlyCallBackData*)pCallBackData;
            StringContent strContent;
            PlyHttpServerReqGetPathMatchIndex(pcbd->bSecureSSL, pRequest, 1, [](int nIndex, const char* pValue, unsigned int nValueSize, void* pUserData)
                {
                    auto pReqContent = (StringContent*)pUserData;
                    pReqContent->content.assign(pValue, nValueSize);
                }, &strContent);
            std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: " + std::to_string(strContent.content.length()) + "\r\n\r\n" + strContent.content;
            PlyHttpServerConnSend(pcbd->bSecureSSL, pcbd->pInstance, pResponse, resp.data(), resp.length(), false);
        });
    PlyHttpServerInit(!bUseSsl, pHttpSSLServer, [](void* pConn, int nErrorCode, const char* pErrorDesc, void* pCallBackData)
        {
        });
    {
        std::thread([bUseSsl, pHttpServer]() { PlyHttpServerStart(bUseSsl, pHttpServer); }).detach();
        std::thread([bUseSsl, pHttpSSLServer]() { PlyHttpServerStart(!bUseSsl, pHttpSSLServer); }).detach();
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::thread([bUseSsl, pHttpClient]() { PlyHttpClientStart(bUseSsl, pHttpClient); }).detach();
        std::thread([bUseSsl, pHttpSSLClient]() { PlyHttpClientStart(!bUseSsl, pHttpSSLClient); }).detach();
        int i = 0;
        while (true)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
            auto msg = ("http ok!" + std::to_string(i++));
            PlyHttpClientSendSync(bUseSsl, pHttpClient, "POST", "/string", msg.c_str(), msg.length(), "", [](void*/* pRequest*/, void* pResponse, void* pCallBackData)
                {
                    PlyCallBackData* pcbd = (PlyCallBackData*)pCallBackData;
                    StringContent strContent;
                    PlyHttpClientRespGetContent(pcbd->bSecureSSL, pResponse, [](int nIndex, const char* pValue, unsigned int nValueSize, void* pUserData)
                        {
                            auto pReqContent = (StringContent*)pUserData;
                            pReqContent->content.assign(pValue, nValueSize);
                        }, &strContent);
                    printf("recv %s,%d\n", strContent.content.c_str(), strContent.content.size());
                }, [](int nErrorCode, const char* pErrorDesc, void* pCallBackData) 
                {
                    printf("pErrorDesc=%s\n", pErrorDesc);
                });
            PlyHttpClientSendSync(bUseSsl, pHttpClient, "GET", "/match/123", msg.c_str(), msg.length(), "", [](void*/* pRequest*/, void* pResponse, void* pCallBackData)
                {
                    PlyCallBackData* pcbd = (PlyCallBackData*)pCallBackData;
                    StringContent strContent;
                    PlyHttpClientRespGetContent(pcbd->bSecureSSL, pResponse, [](int nIndex, const char* pValue, unsigned int nValueSize, void* pUserData)
                        {
                            auto pReqContent = (StringContent*)pUserData;
                            pReqContent->content.assign(pValue, nValueSize);
                        }, &strContent);
                    printf("recv %s,%d\n", strContent.content.c_str(), strContent.content.size());
                }, [](int nErrorCode, const char* pErrorDesc, void* pCallBackData)
                {
                    printf("pErrorDesc=%s\n", pErrorDesc);
                });
            msg = ("https ok!" + std::to_string(i++));
            PlyHttpClientSendSync(!bUseSsl, pHttpSSLClient, "POST", "/string", msg.c_str(), msg.length(), "", [](void*/* pRequest*/, void* pResponse, void* pCallBackData)
                {
                    PlyCallBackData* pcbd = (PlyCallBackData*)pCallBackData;
                    StringContent strContent;
                    PlyHttpClientRespGetContent(pcbd->bSecureSSL, pResponse, [](int nIndex, const char* pValue, unsigned int nValueSize, void* pUserData)
                        {
                            auto pReqContent = (StringContent*)pUserData;
                            pReqContent->content.assign(pValue, nValueSize);
                        }, & strContent);
                    printf("recv %s,%d\n", strContent.content.c_str(), strContent.content.size());
                }, [](int nErrorCode, const char* pErrorDesc, void* pCallBackData)
                {
                    printf("pErrorDesc=%s\n", pErrorDesc);
                });
            PlyHttpClientSendSync(!bUseSsl, pHttpSSLClient, "GET", "/mymatch/123", msg.c_str(), msg.length(), "", [](void*/* pRequest*/, void* pResponse, void* pCallBackData)
                {
                    PlyCallBackData* pcbd = (PlyCallBackData*)pCallBackData;
                    StringContent strContent;
                    PlyHttpClientRespGetContent(pcbd->bSecureSSL, pResponse, [](int nIndex, const char* pValue, unsigned int nValueSize, void* pUserData)
                        {
                            auto pReqContent = (StringContent*)pUserData;
                            pReqContent->content.assign(pValue, nValueSize);
                        }, &strContent);
                    printf("recv %s,%d\n", strContent.content.c_str(), strContent.content.size());
                }, [](int nErrorCode, const char* pErrorDesc, void* pCallBackData)
                {
                    printf("pErrorDesc=%s\n", pErrorDesc);
                });
        }
    }
__LEAVE_CLEAN__:
    if (pHttpServer != NULL)
    {
        PlyHttpServerDestroy(bUseSsl, &pHttpServer);
    }
    if (pHttpClient != NULL)
    {
        PlyHttpClientDestroy(bUseSsl, &pHttpClient);
    }
    if (pHttpSSLServer != NULL)
    {
        PlyHttpServerDestroy(!bUseSsl, &pHttpSSLServer);
    }
    if (pHttpSSLClient != NULL)
    {
        PlyHttpClientDestroy(!bUseSsl, &pHttpSSLClient);
    }
}

下载连接:

链接:https://pan.baidu.com/s/17j029joGHqhRmZIWKlwEJg 

本帖有隐藏内容,请您回复后查看。

本帖有隐藏内容,请您回复后查看。


本帖有隐藏内容,请您回复后查看。


×
打赏作者
最新回复 (0)
只看楼主
全部楼主
返回