Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I send json data and close connection in onWebsocketConnect #1082

Open
thorewi opened this issue Jan 3, 2025 · 3 comments
Open

How can I send json data and close connection in onWebsocketConnect #1082

thorewi opened this issue Jan 3, 2025 · 3 comments

Comments

@thorewi
Copy link

thorewi commented Jan 3, 2025

Hi,

I would like to check Authorization header in onWebsocketConnect event and if it's not valid, send json data with error message and close connection...

so basically I would like to edit this Websocket.php code:

if (!empty($connection->context->tmpWebsocketData)) {
  $connection->send($connection->context->tmpWebsocketData, true);
  $connection->context->tmpWebsocketData = '';
  if ($connection->closeAfterDataSent)
	$connection->close();
  }	
}

or is there any other way?

Thank you.

@fuzqing
Copy link
Contributor

fuzqing commented Jan 3, 2025

你不需要修改 workerman 的源码,具体做法请查看文档关于 WebSocket Protocol 的部分文档。

@thorewi
Copy link
Author

thorewi commented Jan 3, 2025

if you mean call " $connection->close();" it doesnt work because nginx (serving as reverse proxy) throw 502 upstream prematurely closed connection while reading response header from upstream

@fuzqing
Copy link
Contributor

fuzqing commented Jan 3, 2025

好吧,我知道你的意思了,我们可以使用定时器(Timer) 来实现:

use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use Workerman\Worker;
use Workerman\Timer;

require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('websocket://0.0.0.0:12345');
$worker->onWebSocketConnect = function (TcpConnection $connection, Request $request) {
    if ($request->get('token') != 'abc123') {
        $message = [
            'status' => 'error',
            'code' => 401,
            'message' => 'Authentication failed',
            'data' => [
                'reason' => 'Invalid credentials or token expired',
                'suggestion' => 'Please check your username/password or refresh your token.'
            ]
        ];
        $connection->send(json_encode( $message ));
        $time_interval = 0.001;
        Timer::add($time_interval, function() use($connection) {
            $connection->close();
        },null,false);
    }
};
$worker->onMessage = function(TcpConnection $connection, $data)
{
    $connection->send('hello ' . $data);
};
Worker::runAll();`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants