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();
});

运行:

相关推荐
计算机学姐1 分钟前
基于SpringBoot的个人健康管理系统【2026最新】
java·spring boot·后端·mysql·spring·intellij-idea·mybatis
独自破碎E5 分钟前
Spring是怎么解决循环依赖的?
java·后端·spring
dwp114717060729 分钟前
在Windows上基于MSYS2 UCRT64工具链编译ffmpeg源码
windows·ffmpeg
IT_陈寒1 小时前
Redis性能翻倍的5个冷门技巧:从每秒10万到20万的实战优化之路
前端·人工智能·后端
No芒柠Exception2 小时前
Spring Boot 实现分片上传、断点续传与进度条
java·后端
三十_2 小时前
WebRTC 入门:一分钟理解会议系统的三种架构(Mesh/SFU/MCU)
前端·后端·webrtc
嘻哈baby2 小时前
Redis缓存三大问题实战:穿透、雪崩、击穿怎么解决
后端
用户6135411460162 小时前
IE9浏览器在Windows7 64位系统上的安装步骤(中文版)
windows
Cache技术分享2 小时前
282. Java Stream API - 从 Collection 或 Iterator 创建 Stream
前端·后端
用户3074596982072 小时前
ThinkPHP 6.0 多应用模式下的中间件机制详解
后端·thinkphp