Poco C++ Libraries 提供了完整的網路程式設計元件,包含 HTTP/HTTPS Client、WebSocket、SSL/TLS 整合。本文示範如何使用 Poco::Net::WebSocket 搭配 HTTPSClientSession 建立 WSS (WebSocket Secure) 客戶端,連線至 echo.websocket.org 進行測試。
#include "stdafx.h"
#include <iostream>
#include <assert.h>
#include "Poco/Net/WebSocket.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/Net/Context.h"
#include "Poco/Net/AcceptCertificateHandler.h"
#include "Poco/SharedPtr.h"
#include "Poco/Exception.h"
using Poco::Net::HTTPSClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::WebSocket;
using Poco::Net::Context;
using Poco::Net::SSLManager;
using Poco::Net::AcceptCertificateHandler;
using Poco::SharedPtr;
using Poco::Exception;
int main(int argc, char* argv[]) {
char buffer[1024];
int flags = 0;
int n = 0;
std::string payload;
try {
// 1. 初始化 SSL
Poco::Net::initializeSSL();
// 2. 設定 SSL Context:TLSv1.2 Client,載入根憑證,寬鬆驗證模式
SharedPtr pCert = new AcceptCertificateHandler(false);
Context::Ptr pContext = new Context(
Context::TLSV1_2_CLIENT_USE,
"", "", "rootcert.pem", // 憑證檔案路徑
Context::VERIFY_RELAXED, // 驗證模式
9, // 驗證深度
false, // loadDefaultCAs
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH" // cipher list
);
SSLManager::instance().initializeClient(0, pCert, pContext);
// 3. 建立 HTTPS 會話並發送 WebSocket 升級請求
HTTPSClientSession cs("echo.websocket.org", 443);
HTTPRequest request(HTTPRequest::HTTP_GET, "/", "HTTP/1.1");
HTTPResponse response;
WebSocket* ws = new WebSocket(cs, request, response);
// 4. 發送文字框架
payload = "SHAKETHAND";
ws->sendFrame(payload.data(), payload.size(), WebSocket::FRAME_TEXT);
// 5. 接收回應
n = ws->receiveFrame(buffer, sizeof(buffer), flags);
std::cout << "return: " << std::string(buffer, n) << std::endl;
// 6. 關閉連線
ws->shutdown();
delete ws;
}
catch (Exception& ex) {
std::cerr << "Error: " << ex.displayText() << std::endl;
return -1;
}
return 0;
}
initializeSSL() 必須在建立任何 SSL 連線前呼叫一次。AcceptCertificateHandler 接受所有憑證(適合測試),生產環境應改用 ConsoleCertificateHandler 或自訂驗證邏輯,並提供有效的 CA 憑證檔 (rootcert.pem)。VERIFY_RELAXED 允許自簽憑證,正式環境建議 VERIFY_STRICT。WebSocket(cs, request, response) 內部自動發送 Upgrade: websocket 標頭並驗證回應。sendFrame/receiveFrame 支援文字、二進位、關閉、Ping/Pong 等 opcode。find_package(Poco REQUIRED COMPONENTS Net SSL NetSSL_OpenSSL)
target_link_libraries(your_target PRIVATE Poco::Net Poco::NetSSL_OpenSSL Poco::SSL Poco::Foundation)
wss://ws.postman-echo.com/raw)。rootcert.pem 存在且包含目標網站的 CA 鏈,或暫時使用 AcceptCertificateHandler 排除驗證問題。Context::TLSV1_CLIENT_USE),請參考對應版本文件。Poco 的 WebSocket 實作為同步阻塞模式,適合桌面應用、IoT 裝置、後端服務等場景。若需高併發非同步架構,可考慮搭配 Poco::Net::HTTPServer 或第三方庫 (如 Boost.Beast、libwebsockets)。