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