Swoole——创建TCP服务

启动TCP服务代码

<?php
/**
 * 智慧公厕
 */

namespace Toilet\Action;

class IndexAction extends CommonAction
{
    public function server() {
        //创建Server对象,监听 127.0.0.1:25111端口
        $serv = new \Swoole\Server("127.0.0.1", 25111);

        //监听连接进入事件
        $serv->on('Connect', function ($serv, $fd) {
            echo "Client: Connect.\n";
            setlog([$fd],'','&#x8FDE;&#x63A5;','toilet.log');
        });

        //&#x76D1;&#x542C;&#x6570;&#x636E;&#x63A5;&#x6536;&#x4E8B;&#x4EF6;
        $serv->on('Receive', function ($serv, $fd, $from_id, $data) {
            $serv->send($fd, "Server: ".$data);
            setlog([$data,$fd,$from_id],'','&#x54CD;&#x5E94;','toilet.log');
        });

        //&#x76D1;&#x542C;&#x8FDE;&#x63A5;&#x5173;&#x95ED;&#x4E8B;&#x4EF6;
        $serv->on('Close', function ($serv, $fd) {
            echo "Client: Close.\n";
            setlog([$fd],'','&#x5173;&#x95ED;','toilet.log');
        });

        //&#x542F;&#x52A8;&#x670D;&#x52A1;&#x5668;
        $serv->start();
    }
}

执行

php toilet.php Index/server
PHP Fatal error:  Class 'Swoole\Server' not found in /home/wwwroot/default/smart/smart-community/Application/Toilet/Action/IndexAction.class.php on line 12

Fatal error: Class 'Swoole\Server' not found in /home/wwwroot/default/smart/smart-community/Application/Toilet/Action/IndexAction.class.php on line 12
Class 'Swoole\Server' not found
FILE: /home/wwwroot/default/smart/smart-community/Application/Toilet/Action/IndexAction.class.php(12)

报错了,因为swoole没有安装

安装swoole后

php toilet.php Index/server
Client: Connect.

客户端测试

telnet 127.0.0.1 25111
Trying 127.0.0.1...

Connected to 127.0.0.1.

Escape character is '^]'.

hello
Server: hello

Original: https://www.cnblogs.com/jiqing9006/p/16136453.html
Author: TBHacker
Title: Swoole——创建TCP服务

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/546731/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球