swoole 实现 unixSocket 通信

服务端

<?php
$socket = new Co\Socket(AF_UNIX,SOCK_STREAM,0);
$socket->bind("/tmp/server.sock");
$socket->listen(2048);

go(function ()use($socket){
    while(true) {
        echo "Accept: \n";
        $client = $socket->accept();
        if ($client === false) {
            var_dump($socket->errCode);
        } else {
            Swoole\Event::add($client,function($client){
                if(!$client->checkLiveness()){
                    $client->close();
                    Swoole\Event::del($client);
                    return;
                }
                echo $client->fd."****".$client->recv().PHP_EOL;
                $client->send("world");
            });
        }
    }
});

客户端

<?php
$socket = new Co\Socket(AF_UNIX,SOCK_STREAM,0);

go(function () use ($socket) {
    $retval = $socket->connect("/tmp/server.sock");
    while ($retval)
    {
        $socket->send("hello");
        $data = $socket->recv();
        echo "server recv: ".$data.PHP_EOL;
        if (empty($data)) {
            $socket->close();
            break;
        }
        co::sleep(1.0);
    }
});

 

posted @ 2020-09-06 00:54  GPHPER  阅读(534)  评论(0编辑  收藏  举报
TOP