Workerman是一個(gè)純PHP編寫(xiě)的高性能的Socket服務(wù)器框架,用于快速開(kāi)發(fā)長(zhǎng)連接應(yīng)用
composer require workerman/workerman
workerman.php
,并在其中編寫(xiě)以下代碼:<?php
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker();
$worker->count = 4; // 設(shè)置進(jìn)程數(shù)量
$worker->name = 'MyWorker'; // 設(shè)置進(jìn)程名稱
// 設(shè)置監(jiān)聽(tīng)的端口
$worker->listen('0.0.0.0:8080');
// 設(shè)置處理客戶端連接的邏輯
$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;
};
// 運(yùn)行Worker
Worker::runAll();
workerman.php
文件的目錄,然后使用以下命令啟動(dòng)Workerman服務(wù)器:php workerman.php start
這將啟動(dòng)一個(gè)名為MyWorker
的進(jìn)程,監(jiān)聽(tīng)8080端口。你可以根據(jù)需要修改進(jìn)程數(shù)量、名稱和監(jiān)聽(tīng)端口。
Ctrl + C
。這將終止所有Workerman進(jìn)程。注意:在生產(chǎn)環(huán)境中,建議使用進(jìn)程管理工具(如Supervisor或systemd)來(lái)管理Workerman進(jìn)程,以便在需要時(shí)自動(dòng)啟動(dòng)和停止服務(wù)器。