-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
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
Comments
你不需要修改 |
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 |
好吧,我知道你的意思了,我们可以使用定时器(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();` |
perfect, thank you. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
or is there any other way?
Thank you.
The text was updated successfully, but these errors were encountered: