Skip to content

Instantly share code, notes, and snippets.

@lotharthesavior
Last active May 21, 2022 01:25
Show Gist options
  • Save lotharthesavior/6ee0dd689504a0f87e4e89970df65e61 to your computer and use it in GitHub Desktop.
Save lotharthesavior/6ee0dd689504a0f87e4e89970df65e61 to your computer and use it in GitHub Desktop.
OpenSwoole WebSocket with WaitGroup example
<script>
let ws = new WebSocket('ws://127.0.0.1:9502');
ws.send("test 1");
setTimeout(() => ws.send("test 2"), 2000);
</script>
<?php
use Swoole\WebSocket\Server;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\Coroutine\WaitGroup;
$server = new Server("0.0.0.0", 9502);
$server->set([
'worker_num' => 1,
]);
$state = 0;
$wg = new WaitGroup();
$server->on("Start", function(Server $server) {
echo "Swoole WebSocket Server is started at http://127.0.0.1:9502\n";
});
$server->on('Open', function(Server $server, Swoole\Http\Request $request) {
echo "connection open: {$request->fd}\n";
});
$server->on('Message', function(Server $server, Frame $frame) use (&$state, &$wg) {
$currentState = '';
$data = '';
if ($state === 0) {
$wg->add();
echo "waiting..." . PHP_EOL;
$currentState = $state;
$data = $frame->data;
$state = 1;
} else {
echo "released..." . PHP_EOL;
$wg->done();
$currentState = $state;
$data = $frame->data;
$state = 0;
}
$wg->wait(10);
echo "Message for state " . $currentState . ": " . $data . PHP_EOL;
});
$server->on('Close', function(Server $server, int $fd) {
echo "connection close: {$fd}\n";
});
$server->on('Disconnect', function(Server $server, int $fd) {
echo "connection disconnect: {$fd}\n";
});
$server->start();
@lotharthesavior
Copy link
Author

lotharthesavior commented May 18, 2022

Output:

woole WebSocket Server is started at http://127.0.0.1:9502
connection open: 1
waiting...
released...
Message for state 0: test 1
Message for state 1: test 2

@kingIZZZY2
Copy link

Does it work also to wait/resume between $server->on('Message') and $server->on('Request') ? i.e. an HTTP request starts a wait, and a WebSocket message ends the wait.. possible?

@lotharthesavior
Copy link
Author

Yeah, based on our discoveries it works, but only works properly when the server has only 1 worker.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment