Skip to content

Commit

Permalink
Merge pull request #12 from uniondrug/2.x
Browse files Browse the repository at this point in the history
tcp warp headers
  • Loading branch information
xueron authored Apr 26, 2018
2 parents 8f5a626 + 1dd614c commit 7cf58f8
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
9 changes: 9 additions & 0 deletions src/Servitization/Client/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
namespace Uniondrug\Server\Servitization\Client;

use Uniondrug\Http\Response;
use Uniondrug\Packet\Json;
use Uniondrug\Swoole\Client as SwooleClient;

/**
Expand Down Expand Up @@ -84,6 +85,14 @@ protected function wrapResponse($response)
$response = zlib_decode($response);
}
unset($responseHeaders, $code);
} elseif ('tcp' === strtolower($this->scheme)) {
try {
$responseData = Json::decode($response, 1);
$response = $responseData['body'];
$headers = $responseData['headers'];
} catch (\Exception $e) {
// Do nothing
}
}

return new Response($response, $statusCode, $headers);
Expand Down
30 changes: 28 additions & 2 deletions src/Servitization/Server/TCPServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,20 @@ public function doWork(swoole_server $server, $fd, $data, $from_id)
return 0;
}

$request = null;
try {
// 1.Build request object and call app to handle it.
$connectionInfo = $server->connection_info($fd);
$request = $this->createRequest($data, $fd, $connectionInfo);
$response = app()->handleRequest($request);

// 2.Build response data with headers and body
foreach ($response->getHeaders() as $key => $header) {
$responseData['headers'][$key] = $response->getHeaderLine($key);
}
$responseData['body'] = (string) $response->getBody();

// 3.Retrieve socket fd
if (null !== $response->getFileDescriptor()) {
$fd = $response->getFileDescriptor();
}
Expand All @@ -64,13 +74,29 @@ public function doWork(swoole_server $server, $fd, $data, $from_id)

return -1;
}
$server->send($fd, (string) $response->getBody());

// 4.Send data to client
$server->send($fd, Json::encode($responseData));

// 5.Cleanup session data
app()->shutdown($request, $response);

} catch (\Exception $e) {
// 1. Clean up global vars.
if ($request !== null) {
app()->shutdown($request, null);
}
app()->getLogger('framework')->error("TCPServer Error: " . $e->getMessage());

// 2. Build error messages
$res = call_user_func(app()->getConfig()->path('exception.response'), $e);
$server->send($fd, Json::encode($res));
$responseData = [
'headers' => [],
'body' => Json::encode($res),
];

// 3. Send to client
$server->send($fd, Json::encode($responseData));
}

return 0;
Expand Down

0 comments on commit 7cf58f8

Please sign in to comment.