Workerman是一个纯PHP编写的高性能的Socket服务器框架,用于快速开发长连接应用
composer require workerman/workerman
workerman.php
,并在其中编写以下代码:<?php
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker();
$worker->count = 4; // 设置进程数量
$worker->name = 'MyWorker'; // 设置进程名称
// 设置监听的端口
$worker->listen('0.0.0.0:8080');
// 设置处理客户端连接的逻辑
$worker->onConnect = function ($connection) {
echo "New connection: " . $connection->id . PHP_EOL;
};
$worker->onMessage = function ($connection, $data) {
echo "Received message: " . $data . PHP_EOL;
$connection->send("Hello from Workerman!");
};
$worker->onClose = function ($connection) {
echo "Connection closed: " . $connection->id . PHP_EOL;
};
// 运行Worker
Worker::runAll();
workerman.php
文件的目录,然后使用以下命令启动Workerman服务器:php workerman.php start
这将启动一个名为MyWorker
的进程,监听8080端口。你可以根据需要修改进程数量、名称和监听端口。
Ctrl + C
。这将终止所有Workerman进程。注意:在生产环境中,建议使用进程管理工具(如Supervisor或systemd)来管理Workerman进程,以便在需要时自动启动和停止服务器。