1 /*
2 * Copyright (C) 2021 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 #include <sstream>
16 #include <cstring>
17 #include <sys/socket.h>
18 #include "include/sp_server_socket.h"
19 namespace OHOS {
20 namespace SmartPerf {
SpServerSocket()21 SpServerSocket::SpServerSocket() {}
22
~SpServerSocket()23 SpServerSocket::~SpServerSocket()
24 {
25 Close();
26 }
27
Init()28 int SpServerSocket::Init()
29 {
30 sock = socket(AF_INET, SOCK_DGRAM, 0);
31 if (sock < 0) {
32 std::cout << "Socket Create Failed:" << sock << std::endl;
33 }
34 local.sin_family = AF_INET;
35 local.sin_port = htons(sockPort);
36 local.sin_addr.s_addr = htonl(INADDR_ANY);
37 if (::bind(sock, reinterpret_cast<struct sockaddr *>(&local), sizeof(local)) < 0) {
38 std::cout << "Socket Bind failed:" << sock << std::endl;
39 }
40 return 0;
41 }
42
Sendto(std::string & sendBuf)43 int SpServerSocket::Sendto(std::string &sendBuf)
44 {
45 socklen_t len = sizeof(sockaddr_in);
46 sendto(sock, sendBuf.c_str(), sendBuf.size(), 0, reinterpret_cast<struct sockaddr*>(&client), len);
47 return 0;
48 }
49
Close() const50 void SpServerSocket::Close() const
51 {
52 shutdown(sock, SHUT_RD);
53 }
54
Recvfrom()55 int SpServerSocket::Recvfrom()
56 {
57 bzero(rbuf, sizeof(rbuf));
58 socklen_t len = sizeof(sockaddr_in);
59 int l = recvfrom(sock, rbuf, sizeof(rbuf) - 1, 0, reinterpret_cast<struct sockaddr*>(&client), &len);
60 if (l > 0) {
61 std::cout << "Client:" << rbuf << std::endl;
62 }
63 return l;
64 }
65
RecvBuf() const66 std::string SpServerSocket::RecvBuf() const
67 {
68 std::string recvBuf = rbuf;
69 return recvBuf;
70 }
71 }
72 }
73