1212namespace Simps \RpcMultiplex ;
1313
1414use Multiplex \Packer ;
15+ use Multiplex \Packet ;
1516use Multiplex \Serializer \StringSerializer ;
1617use Simps \Application ;
1718use Simps \Listener ;
2122
2223class TcpServer
2324{
25+ /**
26+ * @var Server
27+ */
2428 protected $ _server ;
2529
30+ /**
31+ * @var array
32+ */
2633 protected $ _config ;
2734
28- /** @var \Simps\Route */
35+ /**
36+ * @var Route
37+ */
2938 protected $ _route ;
3039
3140 /**
@@ -75,13 +84,13 @@ public function __construct()
7584
7685 public function onStart (Server $ server )
7786 {
78- Application::echoSuccess ("Swoole WebSocket Server running:ws :// {$ this ->_config ['ip ' ]}: {$ this ->_config ['port ' ]}" );
87+ Application::echoSuccess ("Swoole Multiplex RPC Server running:tcp :// {$ this ->_config ['ip ' ]}: {$ this ->_config ['port ' ]}" );
7988 Listener::getInstance ()->listen ('start ' , $ server );
8089 }
8190
8291 public function onManagerStart (Server $ server )
8392 {
84- Application::echoSuccess ("Swoole WebSocket Server running:ws :// {$ this ->_config ['ip ' ]}: {$ this ->_config ['port ' ]}" );
93+ Application::echoSuccess ("Swoole Multiplex RPC Server running:tcp :// {$ this ->_config ['ip ' ]}: {$ this ->_config ['port ' ]}" );
8594 Listener::getInstance ()->listen ('managerStart ' , $ server );
8695 }
8796
@@ -93,14 +102,23 @@ public function onWorkerStart(Server $server, int $workerId)
93102
94103 public function onReceive (Server $ server , int $ fd , int $ fromId , string $ data )
95104 {
96- Coroutine::create (function () use ($ server , $ fd , $ fromId , $ data ) {
105+ Coroutine::create (function () use ($ server , $ fd , $ data ) {
97106 $ packet = $ this ->packer ->unpack ($ data );
98-
99107 $ id = $ packet ->getId ();
100- $ body = $ packet ->getBody ();
101-
102- /** @var Protocol $protocol */
103- $ protocol = unserialize ($ body );
108+ try {
109+ /** @var Protocol $protocol */
110+ $ protocol = unserialize ($ packet ->getBody ());
111+
112+ $ class = $ protocol ->getClass ();
113+ $ method = $ protocol ->getMethod ();
114+ $ params = $ protocol ->getParams ();
115+ $ protocol ->setResult ((new $ class ())->{$ method }(...$ params ));
116+ $ result = serialize ($ protocol );
117+ } catch (\Throwable $ exception ) {
118+ $ result = serialize ($ protocol ->setError ($ exception ->getCode (), $ exception ->getMessage ()));
119+ } finally {
120+ $ server ->send ($ fd , $ this ->packer ->pack (new Packet ($ id , $ this ->serializer ->serialize ($ result ))));
121+ }
104122 });
105123 }
106124}
0 commit comments