0

As a simple example, say I simply want to increment a counter when someone connects. The code I have is

use Swoole\WebSocket\Server;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;

$server = new Server("0.0.0.0", 9502);
$users = [];

$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){
     global $count;
     array_push($users, $request->fd);
     var_dump($users);
});

Note: fd is simply the connection ID of the user (maybe short for file descriptor?), so I'm basically trying to get a simple array of all the users that have connected - the problem is though, this value isn't persistant between requests - so when the 2nd user connects, the array becomes empty again

Does anyone know of a way to fix this? I know I could use a database, but that seems very wasteful/inefficient when I want to create a realtime site - so that's why I want to store/access all the data within the php script, if possible...without using any external storage

  • 1
    I think you can use https://openswoole.com/docs/modules/swoole-table for that problem. It is saved in shared memory and can be accessed from multiple processes. – Foobar Nov 11 '22 at 09:44

1 Answers1

1

Not tested but basicly do:

<?php

use Swoole\WebSocket\Server;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\Table;

$server = new Server("0.0.0.0", 9502);
$table = new Table(1024);
$table->column('user_id', Swoole\Table::TYPE_STRING, 64);
$table->create();


$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) use ($table) {
    $table->set($request->fd,['user_id'=>$request->fd]);
    var_dump($table->count());
});

Read more about the possibilities here: openswoole.com/docs/modules/swoole-table

Foobar
  • 769
  • 1
  • 4