在現代 C++ 網路程式開發中,Poco C++ Libraries 提供了強大且易用的網路元件。本文將詳細介紹如何使用 Poco 庫建立 WebSocket Secure (WSS) 客戶端,實現加密的即時雙向通訊。
以下展示一個連接到 echo.websocket.org 測試伺服器的 WSS 客戶端完整範例:
#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/ServerSocket.h"
#include "Poco/Net/NetException.h"
#include "Poco/Exception.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/URIStreamOpener.h"
#include "Poco/StreamCopier.h"
#include "Poco/Path.h"
#include "Poco/URI.h"
#include "Poco/SharedPtr.h"
#include "Poco/Exception.h"
#include "Poco/Net/HTTPStreamFactory.h"
#include "Poco/Net/HTTPSStreamFactory.h"
#include "Poco/Net/FTPStreamFactory.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/Net/KeyConsoleHandler.h"
#include "Poco/Net/ConsoleCertificateHandler.h"
#include "Poco/Net/AcceptCertificateHandler.h"
#include "Poco/Net/SecureStreamSocket.h"
#include "Poco/Net/X509Certificate.h"
#include <memory>
using Poco::Net::HTTPSClientSession;
using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPServerRequest;
using Poco::Net::HTTPServerResponse;
using Poco::Net::WebSocket;
using Poco::Net::WebSocketException;
using Poco::Exception;
using Poco::URIStreamOpener;
using Poco::StreamCopier;
using Poco::Path;
using Poco::URI;
using Poco::SharedPtr;
using Poco::Exception;
using Poco::Net::HTTPStreamFactory;
using Poco::Net::HTTPSStreamFactory;
using Poco::Net::FTPStreamFactory;
using Poco::Net::SSLManager;
using Poco::Net::Context;
using Poco::Net::KeyConsoleHandler;
using Poco::Net::PrivateKeyPassphraseHandler;
using Poco::Net::InvalidCertificateHandler;
using Poco::Net::ConsoleCertificateHandler;
using Poco::Net::AcceptCertificateHandler;
using Poco::Net::X509Certificate;
int main(int argc, _TCHAR* argv[])
{
char buffer[1024];
int flags;
int n;
std::string payload;
try
{
// 初始化 SSL
Poco::Net::initializeSSL();
// 設定憑證處理策略:透過主控台詢問使用者
SharedPtr<InvalidCertificateHandler> pCert = new ConsoleCertificateHandler(false);
// 建立 TLS 客戶端上下文
Context::Ptr pContext = new Context(
Context::TLSV1_CLIENT_USE,
"", "", "rootcert.pem",
Context::VERIFY_RELAXED,
9, false,
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"
);
// 初始化 SSL 管理器
SSLManager::instance().initializeClient(0, pCert, pContext);
// 建立 HTTPS 客戶端會話
HTTPSClientSession cs("echo.websocket.org", 443);
HTTPRequest request(HTTPRequest::HTTP_GET, "/", "HTTP/1.1");
HTTPResponse response;
// 升級為 WebSocket 連線
WebSocket* ws = new WebSocket(cs, request, response);
// 發送文字訊息框架
payload = "SHAKETHAND";
ws->sendFrame(payload.data(), payload.size(), WebSocket::FRAME_TEXT);
// 接收回應
n = ws->receiveFrame(buffer, sizeof(buffer), flags);
std::cout << "return:" << std::string(buffer, n) << "\n";
// 正常關閉連線
ws->shutdown();
delete ws;
}
catch (Poco::Exception& ex)
{
std::cout << "Error: " << __FILE__ << ":" << __LINE__ << ":" << ex.displayText() << "\n";
return -1;
}
return 0;
}
程式首先呼叫 initializeSSL() 初始化 OpenSSL 函式庫。接著建立 ConsoleCertificateHandler,當伺服器憑證無法自動驗證時,會提示使用者決定是否信任。Context 物件配置了 TLS 版本、驗證模式(VERIFY_RELAXED)以及加密套件清單。
使用 HTTPSClientSession 建立加密的 TCP 連線,然後發送標準的 HTTP GET 請求並包含 Upgrade: websocket 標頭。WebSocket 建構函式會自動處理握手協議,若成功則返回可用的 WebSocket 物件。
sendFrame() 與 receiveFrame() 分別用於發送與接收 WebSocket 資料框架。範例中發送純文字訊息,接收緩衝區大小為 1024 位元組。實際應用中應根據預期訊息大小調整緩衝區,並處理分片框架(FRAME_OP_BITMASK)。
AcceptCertificateHandler 搭配受信任的 CA 憑證,避免互動式提示HTTPSClientSession::setTimeout() 設定連線與接收逾時std::unique_ptr 或 SharedPtr 確保資源釋放Poco C++ Libraries 提供了清晰的 API 讓開發者快速建立 WSS 客戶端。透過適當的 SSL 上下文配置與錯誤處理,即可構建安全可靠的即時通訊應用。官方文件提供了更多進階範例,包含伺服器端實作、壓縮擴展與自訂子協議等功能。