swoole TCP服务器

<?php
class Tcp{
    const HOST = '127.0.0.1';
    const PROT = '9501';

    public $tcpServer = null;  // 存放tcp连接信息
    public $config = [
        'worker_num' => 8,  // 开启进程数
        'max_request' => 10000  // 当前worker进程 允许收到的最大请求次数
    ];

    public function __construct()
    {
        // 创建server对象 监听127.0.0.1:9501端口
        $this->tcpServer = new Swoole\Server(self::HOST, self::PROT);
        // 设置参数
        $this->tcpServer->set($this->config);
        // 监听新连接进入事件
        $this->tcpServer->on('connect', [$this, 'onConnect']);
        // 监听接收数据事件
        $this->tcpServer->on('receive', [$this, 'onReceive']);
        // 监听连接关闭事件
        $this->tcpServer->on('close', [$this, 'onClose']);

        // 启动服务
        $this->tcpServer->start();
    }

    /**
     * 新的连接进入事件
     * @param $server   Swoole\Server 对象
     * @param $fd   连接的文件描述符
     * @param $reactorId    连接所在的 Reactor 线程 ID
     */
    public function onConnect($server, $fd, $reactorId)
    {
        echo '这是新连接哦 - fd:'. $fd;
    }

    /**
     * 接收到数据时的回调事件
     * @param $server   Swoole\Server 对象
     * @param $fd       连接的文件描述符
     * @param $reactorId    连接所在的 Reactor 线程 ID
     * @param $data     收到的数据内容,可能是文本或者二进制内容
     */
    public function onReceive($server, $fd, $reactorId, $data)
    {
        $message = '我收到你的消息了: - fd:'. $fd. ' - reactorId:'. $reactorId. ' - 消息内容:'. $data;
        // 向客户端发送消息
        $this->tcpServer->send($fd, $message);
    }

    /**
     * 连接关闭事件
     * @param $server   Swoole\Server 对象
     * @param $fd   连接的文件描述符
     * @param $reactorId 来自哪个 reactor 线程,主动 close 关闭时为负数
     */
    public function onClose($server, $fd, $reactorId)
    {
        echo '我断开连接了 - fd:'. $fd. '--- reactorId:'. $reactorId;
    }
}

new Tcp();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值