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 COMMUNICATIONNETSTACK_WEBSOCKET_CLIENT_H
17 #define COMMUNICATIONNETSTACK_WEBSOCKET_CLIENT_H
18 
19 #include <atomic>
20 #include <map>
21 #include <memory>
22 #include <mutex>
23 #include <queue>
24 #include <signal.h>
25 #include <string.h>
26 #include <string>
27 #include <thread>
28 #include <libwebsockets.h>
29 
30 #include "client_context.h"
31 #include "websocket_client_error.h"
32 
33 namespace OHOS {
34 namespace NetStack {
35 namespace WebSocketClient {
36 
37 struct CloseResult {
38     unsigned int code;
39     const char *reason;
40 };
41 
42 struct CloseOption {
43     unsigned int code;
44     const char *reason;
45 };
46 
47 struct ErrorResult {
48     unsigned int errorCode;
49     const char *errorMessage;
50 };
51 
52 struct OpenResult {
53     unsigned int status;
54     const char *message;
55 };
56 
57 struct OpenOptions {
58     std::map<std::string, std::string> headers;
59 };
60 
61 class WebSocketClient {
62 public:
63     WebSocketClient();
64     ~WebSocketClient();
65     typedef void (*OnMessageCallback)(WebSocketClient *client, const std::string &data, size_t length);
66     typedef void (*OnCloseCallback)(WebSocketClient *client, CloseResult closeResult);
67     typedef void (*OnErrorCallback)(WebSocketClient *client, ErrorResult error);
68     typedef void (*OnOpenCallback)(WebSocketClient *client, OpenResult openResult);
69 
70     int Connect(std::string URL, OpenOptions Options);
71     int Send(char *data, size_t length);
72     int Close(CloseOption options);
73     int Registcallback(OnOpenCallback OnOpen, OnMessageCallback onMessage, OnErrorCallback OnError,
74                        OnCloseCallback onclose);
75     int Destroy();
76 
77     OnMessageCallback onMessageCallback_ = nullptr;
78     OnCloseCallback onCloseCallback_ = nullptr;
79     OnErrorCallback onErrorCallback_ = nullptr;
80     OnOpenCallback onOpenCallback_ = nullptr;
81     ClientContext *GetClientContext() const;
82 
83 private:
84     ClientContext *clientContext;
85 };
86 } // namespace WebSocketClient
87 } // namespace NetStack
88 } // namespace OHOS
89 
90 #endif // COMMUNICATIONNETSTACK_WEBSOCKET_CLIENT_H