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 16 #ifndef FOUNDATION_ACE_NAPI_TEST_NATIVE_MODULE_NET_SERVER_NETSERVER_H 17 #define FOUNDATION_ACE_NAPI_TEST_NATIVE_MODULE_NET_SERVER_NETSERVER_H 18 19 #include <cstddef> 20 21 #include "event_target.h" 22 #include "napi/native_api.h" 23 #include "napi/native_node_api.h" 24 #include "uv.h" 25 26 #define EVENT_TYPE_BUFFER_SIZE 64 27 28 struct WriteReq { 29 uv_write_t req = { 0 }; 30 uv_buf_t buf = { 0 }; 31 }; 32 33 struct NetClient { 34 uv_tcp_t tcp = { 0 }; 35 uv_write_t req = { 0 }; 36 uv_buf_t buf = { 0 }; 37 NetClient* next = nullptr; 38 }; 39 40 class NetServer : public EventTarget { 41 NetServer(napi_env env, napi_value thisVar); 42 virtual ~NetServer(); 43 44 public: 45 int Start(int port); 46 void Stop(); 47 48 static napi_value Export(napi_env env, napi_value exports); 49 50 private: 51 // Napi methods and properties 52 static napi_value JS_Constructor(napi_env env, napi_callback_info cbinfo); 53 static napi_value JS_Start(napi_env env, napi_callback_info cbinfo); 54 static napi_value JS_Stop(napi_env env, napi_callback_info cbinfo); 55 static napi_value JS_On(napi_env env, napi_callback_info cbinfo); 56 static napi_value JS_Once(napi_env env, napi_callback_info cbinfo); 57 static napi_value JS_Off(napi_env env, napi_callback_info cbinfo); 58 59 // C function and members 60 static void EchoAlloc(uv_handle_t* handle, size_t suggestedSize, uv_buf_t* buf); 61 static void AfterShutdown(uv_shutdown_t* req, int status); 62 static void AfterWrite(uv_write_t* req, int status); 63 static void AfterRead(uv_stream_t*, ssize_t nread, const uv_buf_t* buf); 64 static void TakeDiffactionsByStatus(uv_stream_t* handle, ssize_t nread, 65 const uv_buf_t* buf, NetServer* that); 66 static void OnClose(uv_handle_t* peer); 67 static void OnServerClose(uv_handle_t* handle); 68 static void OnConnection(uv_stream_t*, int status); 69 70 uv_loop_t* loop_; 71 int serverClosed_; 72 uv_tcp_t tcpServer_; 73 NetClient* clients_; 74 }; 75 76 #endif /* FOUNDATION_ACE_NAPI_TEST_NATIVE_MODULE_NET_SERVER_NETSERVER_H */ 77