国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

Swoole源碼學習-一個server的創建

macg0406 / 864人閱讀

摘要:若參數和字符串相等則返回。大于則返回大于的值,小于則返回小于的值。下面的中是增加一個這里我們顯然設置了主機和端口暫且跳過在這里我們看到調用了中的方法并且將初始化好的等傳了進去,我們追進去線程數

創建一個server

今天我們來研究一下swoole中server相關的源碼(版本是4.3.1),首先我們先從一段簡單代碼開始

</>復制代碼

  1. $http = new SwooleHttpServer("127.0.0.1",9501);
  2. $http->on("request", function ($request, $response) {
  3. $response->header("Content-Type", "text/html; charset=utf-8");
  4. $response->end("

    Hello Swoole. #".rand(1000, 9999)."

    ");
  5. });
  6. $http->start();

上面的代碼在本地起了一個服務監聽9501端口,下圖是瀏覽器請求的接口

好了我們開始,首先分析一下上面的代碼其實是調用了一下SwooleHttpServer這個類,然后分別調用了下面三個方法:

__construct(初始化)

on(注冊事件)

start(啟動server)

這三個方法都在./swoole_server.cc中,初始化是在MINT階段加載swoole時執行的./swoole_http_server.cc中的swoole_http_server_init方法

</>復制代碼

  1. void swoole_http_server_init(int module_number)
  2. {
  3. SWOOLE_INIT_CLASS_ENTRY_EX(swoole_http_server, "SwooleHttpServer", "swoole_http_server", NULL, NULL, swoole_server);
  4. ...
  5. }

上面可以看到一些命名,注意最后的參數,這里繼承了swoole_server,所以上面幾個方法的注冊實際在swoole_server.c中

</>復制代碼

  1. void swoole_server_init(int module_number)
  2. {
  3. SWOOLE_INIT_CLASS_ENTRY(swoole_server, "SwooleServer", "swoole_server", NULL, swoole_server_methods);
  4. ......
  5. }
  6. static zend_function_entry swoole_server_methods[] = {
  7. PHP_ME(swoole_server, __construct, arginfo_swoole_server__construct, ZEND_ACC_PUBLIC)
  8. PHP_ME(swoole_server, on, arginfo_swoole_server_on, ZEND_ACC_PUBLIC)
  9. PHP_ME(swoole_server, start, arginfo_swoole_void, ZEND_ACC_PUBLIC)
  10. ......
  11. }

其他的暫且略過,上面可以看到swoole_server_methods中定義的這三個方法,我們首先來看下__construct這個方法,首先在arginfo_swoole_server__construct中定義了可以接收的參數

</>復制代碼

  1. ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server__construct, 0, 0, 1)
  2. ZEND_ARG_INFO(0, host)//主機
  3. ZEND_ARG_INFO(0, port)//端口
  4. ZEND_ARG_INFO(0, mode)//模式
  5. ZEND_ARG_INFO(0, sock_type)//sock類型
  6. ZEND_END_ARG_INFO()

好了下面我們正式進入__construct方法

__construct(server的構造)

</>復制代碼

  1. static PHP_METHOD(swoole_server, __construct)
  2. {
  3. size_t host_len = 0;
  4. char *serv_host;
  5. zend_long sock_type = SW_SOCK_TCP;//定義默認socket類型SW_SOCK_TCP
  6. zend_long serv_port = 0;
  7. zend_long serv_mode = SW_MODE_PROCESS;//定義默認模式SW_MODE_PROCESS
  8. //only cli env
  9. if (!SWOOLE_G(cli))
  10. {
  11. swoole_php_fatal_error(E_ERROR, "swoole_server only can be used in PHP CLI mode.");
  12. RETURN_FALSE;
  13. }
  14. if (SwooleG.main_reactor)//初始化main_reactor
  15. {
  16. SwooleG.origin_main_reactor = SwooleG.main_reactor;
  17. SwooleG.main_reactor = NULL;
  18. }
  19. if (SwooleG.serv != NULL)//判斷server狀態
  20. {
  21. swoole_php_fatal_error(E_ERROR, "server is running. unable to create swoole_server.");
  22. RETURN_FALSE;
  23. }
  24. swServer *serv = (swServer *) sw_malloc(sizeof (swServer));

上面是分配一塊swServer結構的內存,往下走

</>復制代碼

  1. swServer_init(serv);

初始化 server,我們跟進去,代碼在./src/server/master.cc中,在這里對swServer中的一些配置做了初始化

</>復制代碼

  1. void swServer_init(swServer *serv)
  2. {
  3. swoole_init();

上面的swoole_init重點對SwooleG進行初始化存放swoole一些全局信息,包括

running (啟動狀態,這里設置為1)

enable_coroutine(協程啟用狀態,這里設置為1)

log_fd (日志fd)

write_log

fatal_error

cpu_num

uname

pid

memory_pool

max_sockets (最大sockets數量 這里是1024)

...

往下走

</>復制代碼

  1. //對serv清零
  2. bzero(serv, sizeof(swServer));
  3. //設置默認模式為SW_MODE_BASE
  4. serv->factory_mode = SW_MODE_BASE;
  5. //設置reactor數量,這里是cpu核數 和 SW_REACTOR_MAX_THREAD(8) 取小的
  6. serv->reactor_num = SW_REACTOR_NUM > SW_REACTOR_MAX_THREAD ? SW_REACTOR_MAX_THREAD : SW_REACTOR_NUM;
  7. serv->dispatch_mode = SW_DISPATCH_FDMOD;
  8. //設置默認worker_num跟cpu核數相同
  9. serv->worker_num = SW_CPU_NUM;
  10. //設置最大鏈接數,這里SW_MAX_CONNECTION是100000 和 上面設置的1024 取小顯然 1024
  11. serv->max_connection = SW_MIN(SW_MAX_CONNECTION, SwooleG.max_sockets);
  12. //設置最大等待時間,這里SW_WORKER_MAX_WAIT_TIME為30
  13. serv->max_wait_time = SW_WORKER_MAX_WAIT_TIME;
  14. //http server
  15. serv->http_parse_post = 1;
  16. serv->http_compression = 1;
  17. serv->http_compression_level = 1; // Z_BEST_SPEED
  18. serv->upload_tmp_dir = sw_strdup("/tmp");
  19. serv->buffer_input_size = SW_BUFFER_INPUT_SIZE;
  20. serv->buffer_output_size = SW_BUFFER_OUTPUT_SIZE;
  21. serv->task_ipc_mode = SW_TASK_IPC_UNIXSOCK;
  22. serv->enable_coroutine = 1;
  23. /**
  24. * alloc shared memory(分配共享內存)
  25. */
  26. serv->stats = (swServerStats *) SwooleG.memory_pool->alloc(SwooleG.memory_pool, sizeof(swServerStats));
  27. if (serv->stats == NULL)
  28. {
  29. swError("[Master] Fatal Error: failed to allocate memory for swServer->stats.");
  30. }
  31. serv->gs = (swServerGS *) SwooleG.memory_pool->alloc(SwooleG.memory_pool, sizeof(swServerGS));
  32. if (serv->gs == NULL)
  33. {
  34. swError("[Master] Fatal Error: failed to allocate memory for swServer->gs.");
  35. }
  36. 將server放入SwooleG中
  37. SwooleG.serv = serv;
  38. }

好了,server初始化完成,下面再回到__construct方法中

</>復制代碼

  1. //解析參數校驗參數格式
  2. if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|lll", &serv_host, &host_len, &serv_port, &serv_mode, &sock_type) == FAILURE)
  3. {
  4. swoole_php_fatal_error(E_ERROR, "invalid swoole_server parameters.");
  5. RETURN_FALSE;
  6. }
  7. //如果不是SW_MODE_BASE或者SW_MODE_PROCESS模式報錯,這里可以看到目前server支持這兩種模式
  8. if (serv_mode != SW_MODE_BASE && serv_mode != SW_MODE_PROCESS)
  9. {
  10. swoole_php_fatal_error(E_ERROR, "invalid $mode parameters %d.", (int) serv_mode);
  11. RETURN_FALSE;
  12. }
  13. //SW_MODE_BASE模式重置reactor_num和worker_num為1
  14. if (serv_mode == SW_MODE_BASE)
  15. {
  16. serv->reactor_num = 1;
  17. serv->worker_num = 1;
  18. }
  19. //將serv_mode賦給factory_mode
  20. serv->factory_mode = serv_mode;
  21. //php_sw_server_callbacks清零
  22. bzero(php_sw_server_callbacks, sizeof(zval*) * PHP_SWOOLE_SERVER_CALLBACK_NUM);

函數 strcasecmp()用來比較參數s1和s2字符串,比較時會自動忽略大小寫的差異。若參數s1和s2字符串相等則返回0。s1大于s2則返回大于0 的值,s1 小于s2 則返回小于0的值。下面的if中是增加一個systemd socket.這里我們顯然設置了主機和端口暫且跳過

</>復制代碼

  1. if (serv_port == 0 && strcasecmp(serv_host, "SYSTEMD") == 0)
  2. {
  3. if (swServer_add_systemd_socket(serv) <= 0)
  4. {
  5. swoole_php_fatal_error(E_ERROR, "failed to add systemd socket.");
  6. RETURN_FALSE;
  7. }
  8. }
  9. else
  10. {
  11. swListenPort *port = swServer_add_port(serv, sock_type, serv_host, serv_port);

在這里我們看到調用了master.cc中的swServer_add_port方法并且將初始化好的server,sock_type,serv_host,serv_port等傳了進去,我們追進去

</>復制代碼

  1. if (!port)
  2. {
  3. zend_throw_exception_ex(
  4. swoole_exception_ce_ptr, errno,
  5. "failed to listen server port[%s:" ZEND_LONG_FMT "]. Error: %s[%d].",
  6. serv_host, serv_port, strerror(errno), errno
  7. );
  8. RETURN_FALSE;
  9. }
  10. }
  11. zval *server_object = getThis();
  12. zval connection_iterator_object;
  13. object_init_ex(&connection_iterator_object, swoole_connection_iterator_ce_ptr);
  14. zend_update_property(swoole_server_ce_ptr, server_object, ZEND_STRL("connections"), &connection_iterator_object);
  15. swConnectionIterator *i = (swConnectionIterator *) emalloc(sizeof(swConnectionIterator));
  16. bzero(i, sizeof(swConnectionIterator));
  17. i->serv = serv;
  18. swoole_set_object(&connection_iterator_object, i);
  19. zend_update_property_stringl(swoole_server_ce_ptr, server_object, ZEND_STRL("host"), serv_host, host_len);
  20. zend_update_property_long(swoole_server_ce_ptr, server_object, ZEND_STRL("port"), (long) serv->listen_list->port);
  21. zend_update_property_long(swoole_server_ce_ptr, server_object, ZEND_STRL("mode"), serv->factory_mode);
  22. zend_update_property_long(swoole_server_ce_ptr, server_object, ZEND_STRL("type"), sock_type);
  23. swoole_set_object(server_object, serv);
  24. zval *ports = sw_malloc_zval();
  25. array_init(ports);
  26. server_port_list.zports = ports;
  27. #ifdef HT_ALLOW_COW_VIOLATION
  28. HT_ALLOW_COW_VIOLATION(Z_ARRVAL_P(ports));
  29. #endif
  30. swListenPort *ls;
  31. LL_FOREACH(serv->listen_list, ls)
  32. {
  33. php_swoole_server_add_port(serv, ls);
  34. }
  35. server_port_list.primary_port = (swoole_server_port_property *) serv->listen_list->ptr;
  36. zend_update_property(swoole_server_ce_ptr, server_object, ZEND_STRL("ports"), ports);
  37. }

</>復制代碼

  1. struct _swServer
  2. {
  3. /**
  4. 線程數
  5. * reactor thread/process num
  6. */
  7. uint16_t reactor_num;
  8. /**
  9. * worker process num
  10. */
  11. uint16_t worker_num;
  12. /**
  13. * The number of pipe per reactor maintenance
  14. */
  15. uint16_t reactor_pipe_num;
  16. uint8_t factory_mode;
  17. uint8_t dgram_port_num;
  18. /**
  19. * package dispatch mode
  20. */
  21. uint8_t dispatch_mode;
  22. /**
  23. * No idle work process is available.
  24. */
  25. uint8_t scheduler_warning;
  26. int worker_uid;
  27. int worker_groupid;
  28. /**
  29. * max connection num
  30. */
  31. uint32_t max_connection;
  32. /**
  33. * worker process max request
  34. */
  35. uint32_t max_request;
  36. int udp_socket_ipv4;
  37. int udp_socket_ipv6;
  38. uint32_t max_wait_time;
  39. /*----------------------------Reactor schedule--------------------------------*/
  40. uint16_t reactor_round_i;
  41. uint16_t reactor_next_i;
  42. uint16_t reactor_schedule_count;
  43. sw_atomic_t worker_round_id;
  44. /**
  45. * run as a daemon process
  46. */
  47. uint32_t daemonize :1;
  48. /**
  49. * have dgram socket
  50. */
  51. uint32_t have_dgram_sock :1;
  52. /**
  53. * have stream socket
  54. */
  55. uint32_t have_stream_sock :1;
  56. /**
  57. * open cpu affinity setting
  58. */
  59. uint32_t open_cpu_affinity :1;
  60. /**
  61. * disable notice when use SW_DISPATCH_ROUND and SW_DISPATCH_QUEUE
  62. */
  63. uint32_t disable_notify :1;
  64. /**
  65. * discard the timeout request
  66. */
  67. uint32_t discard_timeout_request :1;
  68. /**
  69. * parse x-www-form-urlencoded data
  70. */
  71. uint32_t http_parse_post :1;
  72. /**
  73. * http content compression
  74. */
  75. uint32_t http_compression :1;
  76. /**
  77. * handle static files
  78. */
  79. uint32_t enable_static_handler :1;
  80. /**
  81. * enable onConnect/onClose event when use dispatch_mode=1/3
  82. */
  83. uint32_t enable_unsafe_event :1;
  84. /**
  85. * waiting for worker onConnect callback function to return
  86. */
  87. uint32_t enable_delay_receive :1;
  88. /**
  89. * asynchronous reloading
  90. */
  91. uint32_t reload_async :1;
  92. /**
  93. * enable coroutine in task worker
  94. */
  95. uint32_t task_enable_coroutine :1;
  96. /**
  97. * slowlog
  98. */
  99. uint32_t trace_event_worker :1;
  100. /**
  101. * yield coroutine when the output buffer is full
  102. */
  103. uint32_t send_yield :1;
  104. /**
  105. * enable coroutine
  106. */
  107. uint32_t enable_coroutine :1;
  108. /**
  109. * disable multi-threads
  110. */
  111. uint32_t single_thread :1;
  112. /**
  113. * heartbeat check time
  114. */
  115. uint16_t heartbeat_idle_time;
  116. uint16_t heartbeat_check_interval;
  117. int *cpu_affinity_available;
  118. int cpu_affinity_available_num;
  119. double send_timeout;
  120. uint16_t listen_port_num;
  121. time_t reload_time;
  122. time_t warning_time;
  123. /* buffer output/input setting*/
  124. uint32_t buffer_output_size;
  125. uint32_t buffer_input_size;
  126. void *ptr2;
  127. void *private_data_3;
  128. swFactory factory;
  129. swListenPort *listen_list;
  130. pthread_t heartbeat_pidt;
  131. /**
  132. * task process
  133. */
  134. uint16_t task_worker_num;
  135. uint8_t task_ipc_mode;
  136. uint16_t task_max_request;
  137. swPipe *task_notify;
  138. swEventData *task_result;
  139. /**
  140. * user process
  141. */
  142. uint16_t user_worker_num;
  143. swUserWorker_node *user_worker_list;
  144. swHashMap *user_worker_map;
  145. swWorker *user_workers;
  146. swReactorThread *reactor_threads;
  147. swWorker *workers;
  148. swChannel *message_box;
  149. swServerStats *stats;
  150. swServerGS *gs;
  151. #ifdef HAVE_PTHREAD_BARRIER
  152. pthread_barrier_t barrier;
  153. #endif
  154. swConnection *connection_list;
  155. swSession *session_list;
  156. /**
  157. * temporary directory for HTTP uploaded file.
  158. */
  159. char *upload_tmp_dir;
  160. /**
  161. * http compression level for gzip/br
  162. */
  163. uint8_t http_compression_level;
  164. /**
  165. * http static file directory
  166. */
  167. char *document_root;
  168. uint16_t document_root_len;
  169. /**
  170. * master process pid
  171. */
  172. char *pid_file;
  173. /**
  174. * stream
  175. */
  176. char *stream_socket;
  177. int stream_fd;
  178. swProtocol stream_protocol;
  179. int last_stream_fd;
  180. swLinkedList *buffer_pool;
  181. #ifdef SW_BUFFER_RECV_TIME
  182. double last_receive_usec;
  183. #endif
  184. int manager_alarm;
  185. /**
  186. * message queue key
  187. */
  188. uint64_t message_queue_key;
  189. /**
  190. * slow request log
  191. */
  192. uint8_t request_slowlog_timeout;
  193. FILE *request_slowlog_file;
  194. swReactor *reactor_ptr; //Main Reactor
  195. swFactory *factory_ptr; //Factory
  196. swLinkedList *hooks[SW_MAX_HOOK_TYPE];
  197. void (*onStart)(swServer *serv);
  198. void (*onManagerStart)(swServer *serv);
  199. void (*onManagerStop)(swServer *serv);
  200. void (*onShutdown)(swServer *serv);
  201. void (*onPipeMessage)(swServer *, swEventData *);
  202. void (*onWorkerStart)(swServer *serv, int worker_id);
  203. void (*onWorkerStop)(swServer *serv, int worker_id);
  204. void (*onWorkerExit)(swServer *serv, int worker_id);
  205. void (*onWorkerError)(swServer *serv, int worker_id, pid_t worker_pid, int exit_code, int signo);
  206. void (*onUserWorkerStart)(swServer *serv, swWorker *worker);
  207. /**
  208. * Client
  209. */
  210. int (*onReceive)(swServer *, swEventData *);
  211. int (*onPacket)(swServer *, swEventData *);
  212. void (*onClose)(swServer *serv, swDataHead *);
  213. void (*onConnect)(swServer *serv, swDataHead *);
  214. void (*onBufferFull)(swServer *serv, swDataHead *);
  215. void (*onBufferEmpty)(swServer *serv, swDataHead *);
  216. /**
  217. * Task Worker
  218. */
  219. int (*onTask)(swServer *serv, swEventData *data);
  220. int (*onFinish)(swServer *serv, swEventData *data);
  221. /**
  222. * Server method
  223. */
  224. int (*send)(swServer *serv, int session_id, void *data, uint32_t length);
  225. int (*sendfile)(swServer *serv, int session_id, char *file, uint32_t l_file, off_t offset, size_t length);
  226. int (*sendwait)(swServer *serv, int session_id, void *data, uint32_t length);
  227. int (*close)(swServer *serv, int session_id, int reset);
  228. int (*notify)(swServer *serv, swConnection *conn, int event);
  229. int (*feedback)(swServer *serv, int session_id, int event);
  230. int (*dispatch_func)(swServer *, swConnection *, swSendData *);
  231. };

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/31580.html

相關文章

  • Swoft 源碼剖析 - Swoole和Swoft那些事 (Http/Rpc服務篇)

    摘要:和服務關系最密切的進程是中的進程組,絕大部分業務處理都在該進程中進行。隨后觸發一個事件各組件通過該事件進行配置文件加載路由注冊。事件每個請求到來時僅僅會觸發事件。服務器生命周期和服務基本一致,詳情參考源碼剖析功能實現 作者:bromine鏈接:https://www.jianshu.com/p/4c0...來源:簡書著作權歸作者所有,本文已獲得作者授權轉載,并對原文進行了重新的排版。S...

    張漢慶 評論0 收藏0
  • Easyswoole 源碼學習和個人解析 目錄

    摘要:易用穩定,本次想通過對的學習和個人解析,吸收框架的思想和設計知識,加強自己對的認知和理解。當然,筆者能力水平有限,后續的文章如有錯誤,還請指出和諒解。目錄如下后續添加文章都會記錄在此服務啟動過程以及主體設計流程源碼解析 前言 swoole是什么?官網的原話介紹是這樣的: Swoole 使用純 C 語言編寫,提供了 PHP 語言的異步多線程服務器,異步 TCP/UDP 網絡客戶端,異步 ...

    CoXie 評論0 收藏0
  • swoole——從入門到放棄(一)

    摘要:進程可以使用函數向進程投遞新的任務。當前的進程在調用回調函數時會將進程狀態切換為忙碌,這時將不再接收新的,當函數返回時會將進程狀態切換為空閑然后繼續接收新的。當進程投遞的任務在中完成時,進程會通過方法將任務處理的結果發送給進程。 swoole——從入門到放棄(一) 一、swoole的源碼包安裝 下載swoole源碼:git clone https://gitee.com/swoole...

    morgan 評論0 收藏0
  • Swoole源碼研究】淺析swooleserver實現

    摘要:的部分是基于以及協議的。例如父進程向中寫入子進程從中讀取子進程向中寫入父進程從中讀取。默認使用對進程進行分配交給對應的線程進行監聽線程收到某個進程的數據后會進行處理值得注意的是這個線程可能并不是發送請求的那個線程。 作者:施洪寶 一. 基礎知識 1.1 swoole swoole是面向生產環境的php異步網絡通信引擎, php開發人員可以利用swoole開發出高性能的server服務。...

    rainyang 評論0 收藏0
  • Swoole入門到實戰(一):PHP7&Swoole源碼安裝、玩轉網絡通信引擎、異步非堵塞I

    摘要:服務重點基本概述協議是基于的一種新的網絡協議。被調用者通過狀態通知機制等來通知調用者,或通過回調函數來處理結果阻塞和非阻塞關注的是調用者等待被調用者返回調用結果時的狀態。 一、PHP7源碼安裝和Swoole源碼編譯安裝 1.1 PHP7源碼安裝 1.1.1 獲取源碼與安裝 ????獲取PHP7源碼:www.php.net tar -xzvf ... # 解壓命令 ./configur...

    weakish 評論0 收藏0

發表評論

0條評論

macg0406

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<