Skip to content

Commit

Permalink
add incoming tcp request for auth user to laravel server
Browse files Browse the repository at this point in the history
  • Loading branch information
BUGOVER committed Jan 23, 2024
1 parent 41d5b5b commit 1215748
Show file tree
Hide file tree
Showing 13 changed files with 305 additions and 49 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "bugover/laravel-websocket",
"description": "An easy to use WebSocket server",
"version": "1.14.6",
"version": "1.14.7",
"keywords": [
"beyondcode",
"laravel-websockets"
Expand Down
19 changes: 18 additions & 1 deletion config/websockets.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
/*
* The maximum request size in kilobytes that is allowed for an incoming WebSocket request.
*/
'max_request_size_in_kb' => 256,
'max_request_size_in_kb' => 256, // * 1024

/*
* This path will be used to register the necessary routes for the package.
Expand Down Expand Up @@ -138,4 +138,21 @@
* `ChannelManager` interface provided by this package.
*/
'channel_manager' => \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManagers\ArrayChannelManager::class,

/**
* Channels name with route
* This field for incoming request on websocket client.
*/
'channels' => [
// prefix channel for all client whisper on front side ex. whisper(`broadcast-data/`, { })
'prefix' => 'broadcast-data',

'queue_handler' => 'default',

// channel_name => route file
'names' => [
'client-web' => 'client',
'client-api' => 'client',
],
]
];
2 changes: 1 addition & 1 deletion src/Console/CleanStatistics.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class CleanStatistics extends Command

protected $description = 'Clean up old statistics from the websocket log.';

public function handle()
public function handle(): void
{
$this->comment('Cleaning WebSocket Statistics...');

Expand Down
2 changes: 1 addition & 1 deletion src/Console/StartWebSocketServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public function __construct()
{
parent::__construct();

$this->loop = Loop::get();
$this->loop = Loop::get(); // LoopFactory::create();
}

/**
Expand Down
62 changes: 62 additions & 0 deletions src/Console/Tcp.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

declare(strict_types=1);

namespace BeyondCode\LaravelWebSockets\Console;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Http\Request;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

/**
* Class Tcp
*
* @package Src\Jobs
*/
class Tcp implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;

/**
* Tcp constructor.
*
* @param object $user
* @param object $data
* @param string $class
* @param array $routes
* @param array $routeData
*/
public function __construct(
protected object $user,
protected object $data,
protected string $class,
protected array $routes,
protected array $routeData
)
{
}

/**
* Execute the job.
*
* @return void
*/
public function handle(): void
{
$broadcast = resolve($this->class);
$method = array_values($this->routes[$this->routeData['url']])[0];

if (!method_exists($broadcast, $method)) {
return;
}

$request = (new Request())->replace(['user' => $this->user, 'data' => (array) $this->data]);
$broadcast->{$method}($request);
}
}
14 changes: 7 additions & 7 deletions src/HttpApi/Controllers/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,28 +127,28 @@ public function onMessage(ConnectionInterface $from, $msg)
$this->checkContentLength($from);
}

public function onClose(ConnectionInterface $connection)
public function onClose(ConnectionInterface $conn)
{
}

public function onError(ConnectionInterface $connection, Exception $exception)
public function onError(ConnectionInterface $conn, Exception $e)
{
if (!$exception instanceof HttpException) {
if (!$e instanceof HttpException) {
return;
}

$responseData = json_encode([
'error' => $exception->getMessage(),
'error' => $e->getMessage(),
]);

$response = new Response($exception->getStatusCode(), [
$response = new Response($e->getStatusCode(), [
'Content-Type' => 'application/json',
'Content-Length' => strlen($responseData),
], $responseData);

$connection->send(Message::toString($response));
$conn->send(Message::toString($response));

$connection->close();
$conn->close();
}

abstract public function __invoke(Request $request);
Expand Down
14 changes: 7 additions & 7 deletions src/Server/Logger/HttpLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,23 +36,23 @@ public function onMessage(ConnectionInterface $connection, $message)
$this->app->onMessage($connection, $message);
}

public function onClose(ConnectionInterface $connection)
public function onClose(ConnectionInterface $conn)
{
$this->app->onClose($connection);
$this->app->onClose($conn);
}

public function onError(ConnectionInterface $connection, Exception $exception)
public function onError(ConnectionInterface $conn, Exception $e)
{
$exceptionClass = get_class($exception);
$exceptionClass = get_class($e);

$message = "Exception `{$exceptionClass}` thrown: `{$exception->getMessage()}`";
$message = "Exception `{$exceptionClass}` thrown: `{$e->getMessage()}`";

if ($this->verbose) {
$message .= $exception->getTraceAsString();
$message .= $e->getTraceAsString();
}

$this->error($message);

$this->app->onError($connection, $exception);
$this->app->onError($conn, $e);
}
}
24 changes: 12 additions & 12 deletions src/Server/Logger/WebsocketsLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,38 +37,38 @@ public function setApp(MessageComponentInterface $app)
return $this;
}

public function onMessage(ConnectionInterface $connection, MessageInterface $message)
public function onMessage(ConnectionInterface $conn, MessageInterface $msg)
{
$this->info(
"{$connection->app->id}: connection id {$connection->socketId} received message: {$message->getPayload()}."
"{$conn->app->id}: connection id {$conn->socketId} received message: {$msg->getPayload()}."
);

$this->app->onMessage(ConnectionLogger::decorate($connection), $message);
$this->app->onMessage(ConnectionLogger::decorate($conn), $msg);
}

public function onClose(ConnectionInterface $connection)
public function onClose(ConnectionInterface $conn)
{
$socketId = $connection->socketId ?? null;
$socketId = $conn->socketId ?? null;

$this->warn("Connection id {$socketId} closed.");

$this->app->onClose(ConnectionLogger::decorate($connection));
$this->app->onClose(ConnectionLogger::decorate($conn));
}

public function onError(ConnectionInterface $connection, Exception $exception)
public function onError(ConnectionInterface $conn, Exception $e)
{
$exceptionClass = get_class($exception);
$exceptionClass = get_class($e);

$appId = $connection->app->id ?? 'Unknown app id';
$appId = $conn->app->id ?? 'Unknown app id';

$message = "{$appId}: exception `{$exceptionClass}` thrown: `{$exception->getMessage()}`.";
$message = "{$appId}: exception `{$exceptionClass}` thrown: `{$e->getMessage()}`.";

if ($this->verbose) {
$message .= $exception->getTraceAsString();
$message .= $e->getTraceAsString();
}

$this->error($message);

$this->app->onError(ConnectionLogger::decorate($connection), $exception);
$this->app->onError(ConnectionLogger::decorate($conn), $e);
}
}
8 changes: 4 additions & 4 deletions src/Server/OriginCheck.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@ public function onMessage(ConnectionInterface $from, $msg)
return $this->_component->onMessage($from, $msg);
}

public function onClose(ConnectionInterface $connection)
public function onClose(ConnectionInterface $conn)
{
return $this->_component->onClose($connection);
return $this->_component->onClose($conn);
}

public function onError(ConnectionInterface $connection, Exception $e)
public function onError(ConnectionInterface $conn, Exception $e)
{
return $this->_component->onError($connection, $e);
return $this->_component->onError($conn, $e);
}
}
5 changes: 3 additions & 2 deletions src/Server/WebSocketServerFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;
use React\Socket\SecureServer;
use React\Socket\Server;
use React\Socket\SocketServer;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Routing\Matcher\UrlMatcher;
Expand Down Expand Up @@ -73,13 +74,13 @@ public function setConsoleOutput(OutputInterface $consoleOutput): static

public function createServer(): IoServer
{
$socket = new SocketServer(uri: "{$this->host}:{$this->port}", loop: $this->loop);
$socket = new SocketServer(uri: "{$this->host}:{$this->port}", loop: $this->loop); // new Server();

if (config('websockets.ssl.local_cert')) {
$socket = new SecureServer($socket, $this->loop, config('websockets.ssl'));
}

$urlMatcher = new UrlMatcher($this->routes, new RequestContext);
$urlMatcher = new UrlMatcher($this->routes, new RequestContext());

$router = new Router($urlMatcher);

Expand Down
53 changes: 53 additions & 0 deletions src/WebSockets/Messages/MessageProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace BeyondCode\LaravelWebSockets\WebSockets\Messages;

use BeyondCode\LaravelWebSockets\Console\Tcp;
use Illuminate\Database\Eloquent\Model;

/**
* Class MessageProvider
*
* @package Service\Socket\Messages
*/
class MessageProvider
{
/**
* MessageProvider constructor.
*
* @param string $routeFile
* @param array $routeData
* @param Model $user
* @param object $data
*/
public function __construct(
protected string $routeFile,
protected array $routeData,
protected Model $user,
protected object $data
) {
}

/**
*
*/
public function routeProvider(): void
{
$routes = require base_path("routes/socket/$this->routeFile.php");
$class = array_keys($routes[$this->routeData['url']])[0];

if (!class_exists($class)) {
return;
}

Tcp::dispatch(
$this->user,
$this->data,
$class,
$routes,
$this->routeData
)->onQueue(config('websockets.channels.queue_handler'));
}
}
Loading

0 comments on commit 1215748

Please sign in to comment.