1 /* 2 * Copyright (c) 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 NET_WEBSOCKET_IMPL_H 17 #define NET_WEBSOCKET_IMPL_H 18 19 #include <functional> 20 #include <map> 21 #include <queue> 22 23 #include "ffi_remote_data.h" 24 #include "ffi_structs.h" 25 #include "net_websocket_connect_context.h" 26 #include "net_websocket_send_context.h" 27 #include "net_websocket_close_context.h" 28 #include "cj_lambda.h" 29 #include "constant.h" 30 31 namespace OHOS::NetStack::NetWebSocket { 32 33 class WebSocketContext; 34 35 using WebSocketCallback = std::function<void(CWebSocketCallbackData *)>; 36 37 class CJWebsocketProxy : public OHOS::FFI::FFIData { 38 DECL_TYPE(CJWebsocketProxy, OHOS::FFI::FFIData); 39 40 public: 41 std::shared_ptr<NetWebSocket::WebSocketContext> GetWebSocketContext(); 42 void SetWebSocketContext(const std::shared_ptr<NetWebSocket::WebSocketContext> &websocketContext); 43 void EmitCallBack(CWebSocketCallbackData *data); 44 45 const std::string &GetWebSocketTextData(); 46 47 void AppendWebSocketTextData(void *data, size_t length); 48 49 const std::string &GetWebSocketBinaryData(); 50 51 void AppendWebSocketBinaryData(void *data, size_t length); 52 53 void SetQueueData(void *data); 54 55 void *GetQueueData(); 56 57 void ClearWebSocketTextData(); 58 59 void ClearWebSocketBinaryData(); 60 61 void AddCallback2Map(int32_t type, WebSocketCallback callback); 62 63 void DelCallback(int32_t type); 64 65 std::optional<WebSocketCallback> FindCallback(int32_t type); 66 private: 67 std::queue<void *> dataQueue_; 68 std::string webSocketTextData_; 69 std::string webSocketBinaryData_; 70 std::mutex dataQueueMutex_; 71 72 std::map<int32_t, WebSocketCallback> eventMap_; 73 std::mutex mutex_; 74 std::mutex contextMutex_; 75 std::shared_ptr<NetWebSocket::WebSocketContext> webSocketContext_; 76 }; 77 78 class CJWebsocketImpl { 79 public: 80 static WebSocketConnectContext* Connect(std::string url, CWebSocketRequestOptions* opt, CJWebsocketProxy *proxy); 81 82 static WebSocketSendContext* Send(CArrUI8 data, CJWebsocketProxy *proxy, bool stringType); 83 84 static WebSocketCloseContext* Close(CWebSocketCloseOptions* opt, CJWebsocketProxy *proxy); 85 86 static bool OnWithProxy(int32_t typeId, void (*callback)(CWebSocketCallbackData *data), CJWebsocketProxy *proxy); 87 88 static bool OffWithProxy(int32_t typeId, CJWebsocketProxy *proxy); 89 }; 90 } 91 #endif