Last active
March 19, 2022 18:39
-
-
Save eslof/d532e080a23fda2eb43636b15487095f to your computer and use it in GitHub Desktop.
swoole process + websocket server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
use Swoole\WebSocket\Server; | |
use Swoole\WebSocket\Frame; | |
const CONCURRENT_MAX = 5; | |
const INPUT_TYPE_COL = 'input'; | |
$server = new Server("0.0.0.0", 9502); | |
$table = new Swoole\Table(CONCURRENT_MAX); | |
$table->column(INPUT_TYPE_COL, Swoole\Table::TYPE_INT, 4); | |
$table->create(); | |
$atomic = new Swoole\Atomic(); | |
$process = new Swoole\Process(function ($process) use ($atomic, $server, $table) { | |
if ($atomic->get() > 0) return; | |
$atomic->add(); | |
while (count($server->connections) > 0) { | |
foreach ($table as $fd=>$row) { | |
$input = InputType::from($row[INPUT_TYPE_COL]); | |
//... | |
} | |
} | |
$atomic->sub(); | |
}); | |
$server->on('message', function (Server $server, Frame $frame) use ($process, $atomic, $table) { | |
if (!($data = json_decode($frame->data, true))) return; | |
if (!isset($data->input) || !is_int($data->input)) return; | |
if ($atomic->get() == 0) $process->start(); | |
$data = array(INPUT_TYPE_COL => $data->input); | |
$table->set($frame->fd, $data); | |
}); | |
$server->addProcess($process); | |
$server->start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment