1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #include "connect_server.h" 17 #include <mutex> 18 #include <shared_mutex> 19 #include <unistd.h> 20 #include "log_wrapper.h" 21 22 namespace OHOS::ArkCompiler::Toolchain { 23 std::shared_mutex g_sendMutex; 24 RunServer()25void ConnectServer::RunServer() 26 { 27 terminateExecution_ = false; 28 webSocket_ = std::make_unique<WebSocket>(); 29 tid_ = pthread_self(); 30 int appPid = getpid(); 31 std::string pidStr = std::to_string(appPid); 32 std::string sockName = pidStr + bundleName_; 33 #if defined(OHOS_PLATFORM) 34 if (!webSocket_->InitUnixWebSocket(sockName)) { 35 return; 36 } 37 #endif 38 while (!terminateExecution_) { 39 #if defined(OHOS_PLATFORM) 40 if (!webSocket_->ConnectUnixWebSocket()) { 41 return; 42 } 43 #endif 44 while (webSocket_->IsConnected()) { 45 std::string message = webSocket_->Decode(); 46 if (!message.empty()) { 47 wsOnMessage_(std::move(message)); 48 } 49 } 50 } 51 } 52 StopServer()53void ConnectServer::StopServer() 54 { 55 LOGI("ConnectServer StopServer"); 56 terminateExecution_ = true; 57 if (webSocket_ != nullptr) { 58 webSocket_->Close(); 59 pthread_join(tid_, nullptr); 60 webSocket_.reset(); 61 } 62 } 63 SendMessage(const std::string & message) const64void ConnectServer::SendMessage(const std::string& message) const 65 { 66 std::unique_lock<std::shared_mutex> lock(g_sendMutex); 67 if (webSocket_ == nullptr) { 68 LOGE("ConnectServer SendReply websocket has been closed unexpectedly"); 69 return; 70 } 71 LOGI("ConnectServer SendReply: %{public}s", message.c_str()); 72 webSocket_->SendReply(message); 73 } 74 } // namespace OHOS::ArkCompiler::Toolchain 75