| 303 | } |
| 304 | |
| 305 | void DiscordRpcClient::OnBackgroundThread(void* args) |
| 306 | { |
| 307 | DiscordRpcClient* _this = static_cast<DiscordRpcClient*>(args); |
| 308 | |
| 309 | // Handshake |
| 310 | char buffer[2048]; |
| 311 | std::size_t bufferSize = formatInto(buffer, "{{\"v\":1,\"client_id\":\"{}\"}}", _this->_clientId); |
| 312 | _this->WriteFrame(Opcodes::Handshake, buffer, bufferSize); |
| 313 | |
| 314 | #if defined(DEATH_TARGET_WINDOWS) |
| 315 | HANDLE hPipe = _this->_hPipe; |
| 316 | OVERLAPPED ov = {}; |
| 317 | ov.hEvent = _this->_hEventRead; |
| 318 | if (!::ReadFile(hPipe, buffer, sizeof(buffer), NULL, &ov)) { |
| 319 | DWORD error = ::GetLastError(); |
| 320 | if (error == ERROR_BROKEN_PIPE) { |
| 321 | _this->_hPipe = INVALID_HANDLE_VALUE; |
| 322 | if (hPipe != INVALID_HANDLE_VALUE) { |
| 323 | ::CloseHandle(hPipe); |
| 324 | } |
| 325 | return; |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | HANDLE waitHandles[] = { _this->_hEventRead, _this->_hEventWrite }; |
| 330 | while (_this->_hPipe != INVALID_HANDLE_VALUE) { |
| 331 | DWORD dwEvent = ::WaitForMultipleObjects(static_cast<DWORD>(arraySize(waitHandles)), waitHandles, FALSE, INFINITE); |
| 332 | switch (dwEvent) { |
| 333 | case WAIT_OBJECT_0: { |
| 334 | DWORD bytesRead; |
| 335 | if (::GetOverlappedResult(hPipe, &ov, &bytesRead, FALSE) && bytesRead > 0) { |
| 336 | Opcodes opcode = (Opcodes)*(std::uint32_t*)&buffer[0]; |
| 337 | std::uint32_t frameSize = *(std::uint32_t*)&buffer[4]; |
| 338 | if (frameSize >= sizeof(buffer)) { |
| 339 | continue; |
| 340 | } |
| 341 | |
| 342 | switch (opcode) { |
| 343 | case Opcodes::Handshake: // Invalid response opcode |
| 344 | case Opcodes::Close: { |
| 345 | _this->_hPipe = INVALID_HANDLE_VALUE; |
| 346 | if (hPipe != INVALID_HANDLE_VALUE) { |
| 347 | ::CloseHandle(hPipe); |
| 348 | } |
| 349 | return; |
| 350 | } |
| 351 | case Opcodes::Ping: { |
| 352 | _this->WriteFrame(Opcodes::Pong, &buffer[8], frameSize); |
| 353 | break; |
| 354 | } |
| 355 | case Opcodes::Frame: { |
| 356 | _this->ProcessInboundFrame(&buffer[8], frameSize, sizeof(buffer) - 8); |
| 357 | break; |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | //if (bytesRead > frameSize + 8) { |
| 362 | // LOGW("Partial read ({} bytes left)", bytesRead - (frameSize + 8)); |
nothing calls this directly
no test coverage detected