This commit is contained in:
parent
7debf9f544
commit
9c8b4e25f1
24
src/libs/MyWebSocketHandler.php
Normal file
24
src/libs/MyWebSocketHandler.php
Normal file
@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App;
|
||||
|
||||
use Workerman\Worker;
|
||||
use Workerman\Connection\TcpConnection;
|
||||
|
||||
class MyWebSocketHandler
|
||||
{
|
||||
public function onConnect(TcpConnection $connection): void
|
||||
{
|
||||
echo "New connection\n";
|
||||
}
|
||||
|
||||
public function onMessage(TcpConnection $connection, string $data): void
|
||||
{
|
||||
$connection->send('Hello ' . $data);
|
||||
}
|
||||
|
||||
public function onClose(TcpConnection $connection): void
|
||||
{
|
||||
echo "Connection closed\n";
|
||||
}
|
||||
}
|
@ -1,27 +1,21 @@
|
||||
<?php
|
||||
// 手动加载类文件
|
||||
require_once __DIR__ . '/libs/MyWebSocketHandler.php';
|
||||
|
||||
use Workerman\Worker;
|
||||
use App\MyWebSocketHandler;
|
||||
|
||||
require_once __DIR__ . '/vendor/autoload.php';
|
||||
|
||||
// Create a Websocket server
|
||||
$handler = new MyWebSocketHandler();
|
||||
|
||||
$ws_worker = new Worker('websocket://0.0.0.0:2346');
|
||||
|
||||
// Emitted when new connection come
|
||||
$ws_worker->onConnect = function ($connection) {
|
||||
echo "New connection\n";
|
||||
};
|
||||
$ws_worker->onConnect = [$handler, 'onConnect'];
|
||||
$ws_worker->onMessage = [$handler, 'onMessage'];
|
||||
$ws_worker->onClose = [$handler, 'onClose'];
|
||||
|
||||
// Emitted when data received
|
||||
$ws_worker->onMessage = function ($connection, $data) {
|
||||
// Send hello $data
|
||||
$connection->send('Hello ' . $data);
|
||||
};
|
||||
|
||||
// Emitted when connection closed
|
||||
$ws_worker->onClose = function ($connection) {
|
||||
echo "Connection closed\n";
|
||||
};
|
||||
|
||||
// Run worker
|
||||
Worker::runAll();
|
||||
// 仅在非测试环境下运行
|
||||
if (!getenv('PHPUNIT_RUNNING')) {
|
||||
Worker::runAll();
|
||||
}
|
8
src/workerman.log
Normal file
8
src/workerman.log
Normal file
@ -0,0 +1,8 @@
|
||||
2025-06-03 14:48:47 pid:6105 Workerman[start.php] start in DEBUG mode
|
||||
2025-06-03 14:48:49 pid:6105 Workerman[start.php] received signal SIGINT
|
||||
2025-06-03 14:48:49 pid:6105 Workerman[start.php] stopping
|
||||
2025-06-03 14:48:49 pid:6105 Workerman[start.php] has been stopped
|
||||
2025-06-03 15:11:55 pid:6213 Workerman[start.php] start in DEBUG mode
|
||||
2025-06-03 15:11:56 pid:6213 Workerman[start.php] received signal SIGINT
|
||||
2025-06-03 15:11:56 pid:6213 Workerman[start.php] stopping
|
||||
2025-06-03 15:11:56 pid:6213 Workerman[start.php] has been stopped
|
Loading…
x
Reference in New Issue
Block a user