• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <shared_mutex>
18 #include <unistd.h>
19 #include "log_wrapper.h"
20 
21 namespace OHOS::ArkCompiler::Toolchain {
22 std::shared_mutex g_sendMutex;
23 
RunServer()24 void ConnectServer::RunServer()
25 {
26     terminateExecution_ = false;
27     webSocket_ = std::make_unique<WebSocket>();
28     tid_ = pthread_self();
29     int appPid = getpid();
30     std::string pidStr = std::to_string(appPid);
31     std::string sockName = pidStr + bundleName_;
32     if (!webSocket_->InitUnixWebSocket(sockName)) {
33         return;
34     }
35     while (!terminateExecution_) {
36         if (!webSocket_->ConnectUnixWebSocket()) {
37             return;
38         }
39         while (webSocket_->IsConnected()) {
40             std::string message = webSocket_->Decode();
41             if (!message.empty()) {
42                 wsOnMessage_(std::move(message));
43             }
44         }
45     }
46 }
47 
StopServer()48 void ConnectServer::StopServer()
49 {
50     LOGI("ConnectServer StopServer");
51     terminateExecution_ = true;
52     if (webSocket_ != nullptr) {
53         webSocket_->Close();
54         pthread_join(tid_, nullptr);
55         webSocket_.reset();
56     }
57 }
58 
SendMessage(const std::string & message) const59 void ConnectServer::SendMessage(const std::string& message) const
60 {
61     std::unique_lock<std::shared_mutex> lock(g_sendMutex);
62     if (webSocket_ == nullptr) {
63         LOGE("ConnectServer SendReply websocket has been closed unexpectedly");
64         return;
65     }
66     LOGI("ConnectServer SendReply: %{public}s", message.c_str());
67     webSocket_->SendReply(message);
68 }
69 } // namespace OHOS::ArkCompiler::Toolchain