• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "napi/native_api.h"
17 #include "network/netstack/net_websocket.h"
18 #include "network/netstack/net_websocket_type.h"
19 #include "hilog/log.h"
20 
21 #include <cstring>
22 
23 #undef LOG_DOMAIN
24 #undef LOG_TAG
25 #define LOG_DOMAIN 0x3200 // 全局domain宏,标识业务领域
26 #define LOG_TAG "WSDEMO"  // 全局tag宏,标识模块日志tag
27 
28 // [Start websocket_build_project]
29 // WebSocket客户端全局变量
30 static struct WebSocket *g_client = nullptr;
31 
onOpen(struct WebSocket * wsClient,WebSocket_OpenResult openResult)32 static void onOpen(struct WebSocket *wsClient, WebSocket_OpenResult openResult)
33 {
34     (void)wsClient;
35     OH_LOG_INFO(LOG_APP, "onOpen: code: %{public}u, reason: %{public}s", openResult.code, openResult.reason);
36 }
37 
onMessage(struct WebSocket * wsClient,char * data,uint32_t length)38 static void onMessage(struct WebSocket *wsClient, char *data, uint32_t length)
39 {
40     (void)wsClient;
41     char *tmp = new char[length + 1];
42     for (uint32_t i = 0; i < length; i++) {
43         tmp[i] = data[i];
44     }
45     tmp[length] = '\0';
46     OH_LOG_INFO(LOG_APP, "onMessage: len: %{public}u, data: %{public}s", length, tmp);
47 }
48 
onError(struct WebSocket * wsClient,WebSocket_ErrorResult errorResult)49 static void onError(struct WebSocket *wsClient, WebSocket_ErrorResult errorResult)
50 {
51     (void)wsClient;
52     OH_LOG_INFO(LOG_APP, "onError: code: %{public}u, message: %{public}s", errorResult.errorCode,
53                 errorResult.errorMessage);
54 }
55 
onClose(struct WebSocket * wsClient,WebSocket_CloseResult closeResult)56 static void onClose(struct WebSocket *wsClient, WebSocket_CloseResult closeResult)
57 {
58     (void)wsClient;
59     OH_LOG_INFO(LOG_APP, "onClose: code: %{public}u, reason: %{public}s", closeResult.code, closeResult.reason);
60 }
61 
ConnectWebsocket(napi_env env,napi_callback_info info)62 static napi_value ConnectWebsocket(napi_env env, napi_callback_info info)
63 {
64     size_t argc = 2;
65     napi_value args[2] = {nullptr};
66     napi_value result;
67 
68     napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
69 
70     size_t length = 0;
71     napi_status status = napi_get_value_string_utf8(env, args[0], nullptr, 0, &length);
72     if (status != napi_ok) {
73         napi_get_boolean(env, false, &result);
74         return result;
75     }
76 
77     if (g_client != nullptr) {
78         OH_LOG_INFO(LOG_APP, "there is already one websocket client running.");
79         napi_get_boolean(env, false, &result);
80         return result;
81     }
82     char *buf = new char[length + 1];
83     std::memset(buf, 0, length + 1);
84     napi_get_value_string_utf8(env, args[0], buf, length + 1, &length);
85     // 创建WebSocket Client对象指针
86     g_client = OH_WebSocketClient_Constructor(onOpen, onMessage, onError, onClose);
87     if (g_client == nullptr) {
88         delete[] buf;
89         napi_get_boolean(env, false, &result);
90         return result;
91     }
92     // 连接buf存放的URL对应的WebSocket服务器
93     int connectRet = OH_WebSocketClient_Connect(g_client, buf, {});
94 
95     delete[] buf;
96     napi_get_boolean(env, connectRet == 0, &result);
97     return result;
98 }
99 // [End websocket_build_project]
100 
SendMessage(napi_env env,napi_callback_info info)101 static napi_value SendMessage(napi_env env, napi_callback_info info)
102 {
103     size_t argc = 1;
104     napi_value args[1] = {nullptr};
105     napi_value result;
106 
107     napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
108 
109     size_t length = 0;
110     napi_status status = napi_get_value_string_utf8(env, args[0], nullptr, 0, &length);
111     if (status != napi_ok) {
112         napi_create_int32(env, -1, &result);
113         return result;
114     }
115 
116     if (g_client == nullptr) {
117         OH_LOG_INFO(LOG_APP, "websocket client not connected.");
118         napi_create_int32(env, WebSocket_ErrCode::WEBSOCKET_CLIENT_NULL, &result);
119         return result;
120     }
121     char *buf = new char[length + 1];
122     std::memset(buf, 0, length + 1);
123     napi_get_value_string_utf8(env, args[0], buf, length + 1, &length);
124     // 发送buf中的消息给服务器
125     int ret = OH_WebSocketClient_Send(g_client, buf, length);
126 
127     delete[] buf;
128     napi_create_int32(env, ret, &result);
129     return result;
130 }
131 
CloseWebsocket(napi_env env,napi_callback_info info)132 static napi_value CloseWebsocket(napi_env env, napi_callback_info info)
133 {
134     napi_value result;
135     if (g_client == nullptr) {
136         OH_LOG_INFO(LOG_APP, "websocket client not connected.");
137         napi_create_int32(env, -1, &result);
138         return result;
139     }
140     // 关闭WebSocket连接
141     int ret = OH_WebSocketClient_Close(g_client, {
142                                                    .code = 0,
143                                                    .reason = "Actively Close",
144                                                });
145     // 释放WebSocket资源并置空
146     OH_WebSocketClient_Destroy(g_client);
147     g_client = nullptr;
148     napi_create_int32(env, ret, &result);
149     return result;
150 }
151 
152 EXTERN_C_START
Init(napi_env env,napi_value exports)153 static napi_value Init(napi_env env, napi_value exports)
154 {
155     napi_property_descriptor desc[] = {
156         {"Connect", nullptr, ConnectWebsocket, nullptr, nullptr, nullptr, napi_default, nullptr},
157         {"Send", nullptr, SendMessage, nullptr, nullptr, nullptr, napi_default, nullptr},
158         {"Close", nullptr, CloseWebsocket, nullptr, nullptr, nullptr, napi_default, nullptr},
159     };
160     napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
161     return exports;
162 }
163 EXTERN_C_END
164 
165 static napi_module demoModule = {
166     .nm_version = 1,
167     .nm_flags = 0,
168     .nm_filename = nullptr,
169     .nm_register_func = Init,
170     .nm_modname = "entry",
171     .nm_priv = ((void *)0),
172     .reserved = {0},
173 };
174 
RegisterEntryModule(void)175 extern "C" __attribute__((constructor)) void RegisterEntryModule(void) { napi_module_register(&demoModule); }