windows 搭建 swoole开发环境(官网已支持)

第一步下载:swoole官网下载 swoole-cli-v5.0.3-cygwin-x64.zip 只支持 64 位的系统
第二步解压到指定文件夹:E:\phpstudy_pro\WWW\swoole-cli-v5.0.3-cygwin-x64
第三步设置环境变量:把解压后的文件夹下的 bin 目录路径配置到系统的 Path 环境变量中,确定保存
第四步检查安装情况:打开CMD命令行输入:swoole-cli -v,安装成功
第五步:编写简单的TCP服务器代码:TCP.php

1. 服务端:

php 复制代码
<?php

class TCP
{

    private $server = null;

    public function __construct()
    {
        $this->server = new Swoole\Server('127.0.0.1', 9501);

        $this->server->set(array(
            'worker_num' => 4,     // 进程数
            'max_request' => 50,    // 每个进程最大接受请求数
        ));

        //监听连接进入事件。
        $this->server->on('Connect', [$this, 'onConnect']);

        //监听数据接收事件。
        $this->server->on('Receive', [$this, 'onReceive']);

        监听连接关闭事件。
        $this->server->on('Close', [$this, 'onClose']);

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

    public function onConnect($server, $fd)
    {
        echo "客户端id: {$fd}连接.\n";
    }

    public function onReceive($server, $fd, $reactor_id, $data)
    {
        $server->send($fd, "发送的数据: {$data}");
    }

    public function onClose($server, $fd)
    {
        echo "客户端id: {$fd}关闭.\n";
    }

}


new TCP();

运行:

2. 客户端:

php 复制代码
<?php

use Swoole\Coroutine\Client;
use function Swoole\Coroutine\run;

run(function () {
    $client = new Client(SWOOLE_SOCK_TCP);
    if (!$client->connect('127.0.0.1', 9501, 0.5)) {
        echo "connect failed. Error: {$client->errCode}\n";
    }

    fwrite(STDOUT, '请输入');
    $res = fgets(STDIN);
    $client->send($res);
    echo $client->recv();
    $client->close();
});

运行:

相关推荐
小天源24 分钟前
Error 1053 Error 1067 服务“启动后立即停止” Java / Python 程序无法后台运行 windows nssm注册器下载与报错处理
开发语言·windows·python·nssm·error 1053·error 1067
十五年专注C++开发2 小时前
MinHook:Windows 平台下轻量级、高性能的钩子库
c++·windows·钩子技术·minhook
dongdonglele5214 小时前
ros2环境安装
windows
muinomarts4 小时前
【Windows挂载夸克网盘到本地 AList+Raidrive】
windows
Sharewinfo_BJ5 小时前
PowerBI 2026年1月功能更新|效率升级,体验再优化
windows·microsoft·powerbi
yaoxin5211236 小时前
314. Java Stream API - 使用 Collectors.partitioningBy() 分区元素
java·windows
计算机程序设计小李同学6 小时前
基于 Spring Boot + Vue 的龙虾专营店管理系统的设计与实现
java·spring boot·后端·spring·vue
云小逸7 小时前
【windows核心编程】Windows GDI编程深度解析:从消息循环到双缓冲动画的完整实现
windows
Charlie_lll8 小时前
力扣解题-[3379]转换数组
数据结构·后端·算法·leetcode
VX:Fegn08959 小时前
计算机毕业设计|基于springboot + vue云租车平台系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计