創建一個簡單的tcp服務,可持續的監聽客戶端的鏈接和請求php
libeventsocket
stream sockettcp
EV_READ | EV_PERSISToop
要義libevent對
stream_socket_server
和stream_socket_accept
產生的資源進行監聽code
<?php /** * tcp 服務 socket鏈接 */ $base = event_base_new(); $event = event_new(); // 建立一個socket服務 $serv = stream_socket_server('0.0.0.0:8080'); // 設置對這個socket的事件監聽,監聽可持續讀 event_set($event, $serv, EV_READ|EV_PERSIST, 'server_connect',[$event,$base]); event_base_set($event, $base); event_add($event); // 事件循環監聽 event_base_loop($base); function server_connect($fd,$flags,$args) { $event = $args[0]; $base = $args[1]; echo "client connect...\n"; // 接收socket鏈接 $socket = stream_socket_accept($fd); $new_base = event_base_new(); $new_event = event_new(); // 對該鏈接進行監聽,注意此處,若是創建了鏈接不對其進行accpet,那麼將持續循環 event_set($new_event,$socket,EV_READ|EV_PERSIST,'get',[$new_event,$new_base]); event_base_set($new_event,$new_base); event_add($new_event); event_base_loop($new_base); } function get($fd,$flags,$args) { // 若是鏈接可讀,讀取內容 $buffer = fread($fd, 10000); echo "client send:$buffer\n"; // 發送給客戶端內容 fwrite($fd,'Server:i have got your words -'.$buffer."\n"); }