1 /*
2  * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development 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 "udp_client.h"
17 #include <unistd.h>
18 #include "common/common_macro.h"
19 #include "common/media_log.h"
20 #include "network/socket/socket_utils.h"
21 #include "network/socket/udp_socket.h"
22 #include "utils/utils.h"
23 namespace OHOS {
24 namespace Sharing {
25 
~UdpClient()26 UdpClient::~UdpClient()
27 {
28     SHARING_LOGD("trace.");
29     Disconnect();
30 }
31 
UdpClient()32 UdpClient::UdpClient()
33 {
34     SHARING_LOGD("trace.");
35 }
36 
Connect(const std::string &peerHost, uint16_t peerPort, const std::string &localIp, uint16_t localPort)37 bool UdpClient::Connect(const std::string &peerHost, uint16_t peerPort, const std::string &localIp, uint16_t localPort)
38 {
39     SHARING_LOGI("peerIp: %{public}s, peerPort: %{public}d, localPort: %{public}d, thread_id: %{public}llu.",
40                  GetAnonyString(peerHost).c_str(), peerPort, localPort, GetThreadId());
41     std::unique_lock<std::shared_mutex> lk(mutex_);
42     int32_t retCode = 0;
43     socket_ = std::make_unique<UdpSocket>();
44     if (socket_) {
45         if (socket_->Connect(peerHost, peerPort, retCode, false, true, localIp, localPort)) {
46             SHARING_LOGI("connect success.");
47             auto eventRunner = OHOS::AppExecFwk::EventRunner::Create(true);
48             eventHandler_ = std::make_shared<UdpClientEventHandler>();
49             eventHandler_->SetClient(shared_from_this());
50             eventHandler_->SetEventRunner(eventRunner);
51             eventRunner->Run();
52 
53             eventListener_ = std::make_shared<UdpClientEventListener>();
54             eventListener_->SetClient(shared_from_this());
55 
56             bool ret = eventListener_->AddFdListener(socket_->GetLocalFd(), eventListener_, eventHandler_);
57 
58             auto callback = callback_.lock();
59             if (callback) {
60                 callback->OnClientConnect(true);
61             }
62 
63             return ret;
64         }
65     }
66     auto callback = callback_.lock();
67     if (callback) {
68         callback->OnClientConnect(false);
69     }
70     SHARING_LOGE("connect failed!");
71     return false;
72 }
73 
Disconnect()74 void UdpClient::Disconnect()
75 {
76     SHARING_LOGD("trace.");
77     std::unique_lock<std::shared_mutex> lk(mutex_);
78     if (socket_ != nullptr) {
79         eventListener_->RemoveFdListener(socket_->GetLocalFd());
80         SocketUtils::ShutDownSocket(socket_->GetLocalFd());
81         SocketUtils::CloseSocket(socket_->GetLocalFd());
82         socket_.reset();
83     }
84 }
85 
Send(const DataBuffer::Ptr &buf, int32_t nSize)86 bool UdpClient::Send(const DataBuffer::Ptr &buf, int32_t nSize)
87 {
88     SHARING_LOGD("trace.");
89     RETURN_FALSE_IF_NULL(buf);
90     return Send(buf->Peek(), nSize);
91 }
92 
Send(const char *buf, int32_t nSize)93 bool UdpClient::Send(const char *buf, int32_t nSize)
94 {
95     SHARING_LOGD("trace.");
96     std::unique_lock<std::shared_mutex> lk(mutex_);
97     if (socket_ != nullptr) {
98         int32_t fd = socket_->GetLocalFd();
99         SHARING_LOGD("send fd: %{public}d.", fd);
100         if (::write(fd, buf, nSize) != -1) {
101             return true;
102         } else {
103             if (socket_) {
104                 MEDIA_LOGE("send [%{public}s:%{public}d]Failed, %{public}s.",
105                            GetAnonyString(socket_->GetPeerIp()).c_str(), (int32_t)socket_->GetPeerPort(),
106                            strerror(errno));
107             }
108 
109             return false;
110         }
111     } else {
112         return false;
113     }
114 }
115 
Send(const std::string &msg)116 bool UdpClient::Send(const std::string &msg)
117 {
118     SHARING_LOGD("trace.");
119     return Send(msg.c_str(), msg.size());
120 }
121 
GetSocketInfo()122 SocketInfo::Ptr UdpClient::GetSocketInfo()
123 {
124     SHARING_LOGD("trace.");
125     return socket_;
126 }
127 
OnClientReadable(int32_t fd)128 void UdpClient::OnClientReadable(int32_t fd)
129 {
130     MEDIA_LOGI("fd: %{public}d, thread_id: %{public}llu.", fd, GetThreadId());
131     int32_t retCode = 0;
132     do {
133         DataBuffer::Ptr buf = std::make_shared<DataBuffer>(DEAFULT_READ_BUFFER_SIZE);
134         int32_t retCode = read(fd, buf->Data(), DEAFULT_READ_BUFFER_SIZE);
135         MEDIA_LOGD("recvSocket len: %{public}d.", retCode);
136         if (retCode > 0) {
137             buf->UpdateSize(retCode);
138             auto callback = callback_.lock();
139             if (callback) {
140                 callback->OnClientReadData(fd, std::move(buf));
141             }
142         } else if (retCode == 0) {
143             SHARING_LOGE("recvSocket failed, error:%{public}s!", strerror(errno));
144             Disconnect();
145         }
146     } while (retCode > 0);
147 }
148 } // namespace Sharing
149 } // namespace OHOS
150