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進程,以便在需要時自動啟動和停止服務器。