使用SwooleTable
1.定义Table,支持定义多个Table。
Swoole启动之前会创建定义的所有Table。
- // 在"config/laravels.php"配置
- [
- // ...
- 'swoole_tables' => [
- // 场景:WebSocket中UserId与FD绑定
- 'ws' => [// Key为Table名称,使用时会自动添加Table后缀,避免重名。这里定义名为wsTable的Table
- 'size' => 102400,//Table的最大行数
- 'column' => [// Table的列定义
- ['name' => 'value', 'type' => \Swoole\Table::TYPE_INT, 'size' => 8],
- ],
- ],
- //...继续定义其他Table
- ],
- // ...
- ];
2.访问Table:所有的Table实例均绑定在SwooleServer
上,通过app('swoole')->xxxTable
访问。
- use Swoole\Http\Request;
- use Swoole\WebSocket\Frame;
- use Swoole\WebSocket\Server;
- // 场景:WebSocket中UserId与FD绑定
- public function onOpen(Server $server, Request $request)
- {
- // var_dump(app('swoole') === $server);// 同一实例
- $userId = mt_rand(1000, 10000);
- app('swoole')->wsTable->set('uid:' . $userId, ['value' => $request->fd]);// 绑定uid到fd的映射
- app('swoole')->wsTable->set('fd:' . $request->fd, ['value' => $userId]);// 绑定fd到uid的映射
- $server->push($request->fd, 'Welcome to LaravelS');
- }
- public function onMessage(Server $server, Frame $frame)
- {
- foreach (app('swoole')->wsTable as $key => $row) {
- if (strpos($key, 'uid:') === 0 && $server->exist($row['value'])) {
- $server->push($row['value'], 'Broadcast: ' . date('Y-m-d H:i:s'));// 广播
- }
- }
- }
- public function onClose(Server $server, $fd, $reactorId)
- {
- $uid = app('swoole')->wsTable->get('fd:' . $fd);
- if ($uid !== false) {
- app('swoole')->wsTable->del('uid:' . $uid['value']);// 解绑uid映射
- }
- app('swoole')->wsTable->del('fd:' . $fd);// 解绑fd映射
- $server->push($fd, 'Goodbye');
- }