1

目标

建立一个简单的tcp服务,可持续的监听客户端的连接和请求

细节

  1. libevent

  2. stream socket

  3. EV_READ | EV_PERSIST

代码

要义libevent对stream_socket_serverstream_socket_accept产生的资源进行监听

<?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");

}

jaysun
507 声望25 粉丝

Code is law