Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "WebSocketClient.h"
- WebSocketClient::WebSocketClient() {
- hSession = WinHttpOpen(L"WebSocket Client/Andromeda",
- WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
- WINHTTP_NO_PROXY_NAME,
- WINHTTP_NO_PROXY_BYPASS, 0);
- }
- WebSocketClient::~WebSocketClient() {
- if (hWebSocket) WinHttpWebSocketClose(hWebSocket, WINHTTP_WEB_SOCKET_SUCCESS_CLOSE_STATUS, NULL, 0);
- if (hRequest) WinHttpCloseHandle(hRequest);
- if (hConnect) WinHttpCloseHandle(hConnect);
- if (hSession) WinHttpCloseHandle(hSession);
- }
- bool WebSocketClient::Connect(const wchar_t* host, int port, const wchar_t* path) {
- hConnect = WinHttpConnect(hSession, host, port, 0);
- if (!hConnect) return false;
- hRequest = WinHttpOpenRequest(hConnect, L"GET", path,
- NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
- if (!hRequest) return false;
- // Request protocol upgrade from HTTP to WebSocket.
- WinHttpSetOption(hRequest, WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, 0, 0);
- // Send the request.
- if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0,
- WINHTTP_NO_REQUEST_DATA, 0, 0, 0))
- return false;
- if (!WinHttpReceiveResponse(hRequest, 0))
- return false;
- hWebSocket = WinHttpWebSocketCompleteUpgrade(hRequest, NULL);
- if (!hWebSocket)
- return false;
- // The hRequest handle is not needed anymore. The hWebSocket handle
- // will be used to represent the connection.
- WinHttpCloseHandle(hRequest);
- hRequest = NULL;
- return true;
- }
- bool WebSocketClient::Send(const json& j) const {
- std::string message = j.dump();
- return WinHttpWebSocketSend(hWebSocket, WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE,
- (PVOID)message.c_str(), message.length()) == NO_ERROR;
- }
- std::string WebSocketClient::Receive() const {
- char buffer[1024]{};
- DWORD bytesRead = 0;
- WINHTTP_WEB_SOCKET_BUFFER_TYPE bufferType;
- if (WinHttpWebSocketReceive(hWebSocket, buffer, sizeof(buffer), &bytesRead, &bufferType) == NO_ERROR) {
- return std::string(buffer, bytesRead);
- }
- return "";
- }
- bool WebSocketClient::CheckConnection() const {
- // How?
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement