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 #ifndef SOCKET_CLIENT_H 17 #define SOCKET_CLIENT_H 18 19 #include <map> 20 #include <mutex> 21 22 #include "i_tunnel_client.h" 23 #include "net_packet.h" 24 #include "proto.h" 25 #include "socket_connection.h" 26 #include "stream_client.h" 27 28 namespace OHOS { 29 namespace Msdp { 30 namespace DeviceStatus { 31 typedef std::function<void()> ConnectCallback; 32 class SocketClient final : public StreamClient { 33 public: 34 SocketClient(std::shared_ptr<ITunnelClient> tunnel); 35 DISALLOW_COPY_AND_MOVE(SocketClient); 36 ~SocketClient() = default; 37 38 bool RegisterEvent(MessageId id, std::function<int32_t(const StreamClient&, NetPacket&)> callback); 39 void Start(); 40 void Stop() override; 41 void RegisterConnectedFunction(ConnectCallback funConnected); 42 void RegisterDisconnectedFunction(ConnectCallback funDisconnected); 43 44 private: 45 bool Connect(); 46 int32_t Socket() override; 47 void OnPacket(NetPacket &pkt); 48 void OnDisconnected() override; 49 void Reconnect(); 50 void OnMsgHandler(const StreamClient &client, NetPacket &pkt); 51 52 std::weak_ptr<ITunnelClient> tunnel_; 53 mutable std::mutex lock_; 54 std::map<MessageId, std::function<int32_t(const StreamClient&, NetPacket&)>> callbacks_; 55 std::shared_ptr<SocketConnection> socket_ { nullptr }; 56 std::shared_ptr<AppExecFwk::EventHandler> eventHandler_ { nullptr }; 57 ConnectCallback funConnected_ { nullptr }; 58 ConnectCallback funDisconnected_ { nullptr }; 59 }; 60 } // namespace DeviceStatus 61 } // namespace Msdp 62 } // namespace OHOS 63 #endif // SOCKET_CLIENT_H