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_CONNECTION_H
17 #define SOCKET_CONNECTION_H
18
19 #include <functional>
20 #include <memory>
21
22 #include "file_descriptor_listener.h"
23 #include "nocopyable.h"
24
25 #include "circle_stream_buffer.h"
26 #include "net_packet.h"
27 #include "stream_socket.h"
28
29 namespace OHOS {
30 namespace Msdp {
31 namespace DeviceStatus {
32 class SocketConnection final : public AppExecFwk::FileDescriptorListener, StreamSocket {
33 public:
34 SocketConnection(int32_t socketFd,
35 std::function<void(NetPacket&)> recv,
36 std::function<void()> onDisconnected);
37 ~SocketConnection();
38 DISALLOW_COPY_AND_MOVE(SocketConnection);
39
40 int32_t GetFd() const;
41
42 void OnReadable(int32_t fd) override;
43 void OnShutdown(int32_t fd) override;
44 void OnException(int32_t fd) override;
45
46 static std::shared_ptr<SocketConnection> Connect(std::function<int32_t()> socket,
47 std::function<void(NetPacket&)> recv, std::function<void()> onDisconnected);
48
49 private:
50 int32_t socketFd_ { -1 };
51 std::function<void(NetPacket&)> recv_;
52 std::function<void()> onDisconnected_;
53 CircleStreamBuffer buffer_;
54 };
55
GetFd()56 inline int32_t SocketConnection::GetFd() const
57 {
58 return socketFd_;
59 }
60 } // namespace DeviceStatus
61 } // namespace Msdp
62 } // namespace OHOS
63 #endif // SOCKET_CONNECTION_H