Skip to content

Commit 8b71ff0

Browse files
committed
add onHandShake to InteractsWithWebsocket
1 parent cfd9f90 commit 8b71ff0

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

src/Concerns/InteractsWithWebsocket.php

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,46 @@ public function onOpen($server, $swooleRequest)
8888
}
8989
}
9090

91+
/**
92+
* @param \Swoole\Http\Request $swooleRequest
93+
* @param \Swoole\Http\Response $response
94+
*
95+
* @return bool
96+
* @throws \Illuminate\Contracts\Container\BindingResolutionException
97+
*/
98+
public function onHandShake($swooleRequest, $response)
99+
{
100+
$illuminateRequest = Request::make($swooleRequest)->toIlluminate();
101+
$websocket = $this->app->make(Websocket::class);
102+
$sandbox = $this->app->make(Sandbox::class);
103+
$handler = $this->container->make('config')->get('swoole_websocket.handshake.handler');
104+
105+
try {
106+
$websocket->reset(true)->setSender($swooleRequest->fd);
107+
// set currnt request to sandbox
108+
$sandbox->setRequest($illuminateRequest);
109+
// enable sandbox
110+
$sandbox->enable();
111+
112+
if (! $this->app->make($handler)->handle($swooleRequest, $response)) {
113+
return false;
114+
}
115+
// trigger 'connect' websocket event
116+
if ($websocket->eventExists('connect')) {
117+
// set sandbox container to websocket pipeline
118+
$websocket->setContainer($sandbox->getApplication());
119+
$websocket->call('connect', $illuminateRequest);
120+
}
121+
122+
return true;
123+
} catch (Throwable $e) {
124+
$this->logServerError($e);
125+
} finally {
126+
// disable and recycle sandbox resource
127+
$sandbox->disable();
128+
}
129+
}
130+
91131
/**
92132
* "onMessage" listener.
93133
*
@@ -222,7 +262,9 @@ protected function prepareWebsocket()
222262
$parser = $config->get('swoole_websocket.parser');
223263

224264
if ($isWebsocket) {
225-
$this->events = array_merge($this->events ?? [], $this->wsEvents);
265+
$handshake = $config->get('swoole_websocket.handshake.enabled');
266+
267+
$this->events = array_merge($this->events ?? [], array_merge($this->wsEvents, $handshake ? ['handshake'] : []));
226268
$this->isServerWebsocket = true;
227269
$this->prepareWebsocketRoom();
228270
$this->setPayloadParser(new $parser);

0 commit comments

Comments
 (0)