1111 */
1212namespace Hyperf \WebSocketServer ;
1313
14+ use Hyperf \Contract \ConfigInterface ;
1415use Hyperf \Contract \StdoutLoggerInterface ;
16+ use Hyperf \Server \CoroutineServer ;
1517use Hyperf \WebSocketServer \Exception \InvalidMethodException ;
1618use Psr \Container \ContainerInterface ;
19+ use Swoole \Http \Response ;
1720use Swoole \Server ;
1821
1922/**
@@ -36,23 +39,45 @@ class Sender
3639 */
3740 protected $ workerId ;
3841
42+ /**
43+ * @var Response[]
44+ */
45+ protected $ responses = [];
46+
47+ /**
48+ * @var bool
49+ */
50+ protected $ isCoroutineServer = false ;
51+
3952 public function __construct (ContainerInterface $ container )
4053 {
4154 $ this ->container = $ container ;
4255 $ this ->logger = $ container ->get (StdoutLoggerInterface::class);
56+ if ($ config = $ container ->get (ConfigInterface::class)) {
57+ $ this ->isCoroutineServer = $ config ->get ('server.type ' ) === CoroutineServer::class;
58+ }
4359 }
4460
4561 public function __call ($ name , $ arguments )
4662 {
47- if (! $ this ->proxy ($ name , $ arguments )) {
63+ $ fd = $ this ->getFdFromProxyMethod ($ name , $ arguments );
64+
65+ if ($ this ->isCoroutineServer ) {
66+ if (isset ($ this ->responses [$ fd ])) {
67+ array_shift ($ arguments );
68+ $ this ->responses [$ fd ]->push (...$ arguments );
69+ $ this ->logger ->debug ("[WebSocket] Worker send to # {$ fd }" );
70+ }
71+ return ;
72+ }
73+
74+ if (! $ this ->proxy ($ fd , $ arguments )) {
4875 $ this ->sendPipeMessage ($ name , $ arguments );
4976 }
5077 }
5178
52- public function proxy (string $ name , array $ arguments ): bool
79+ public function proxy (int $ fd , array $ arguments ): bool
5380 {
54- $ fd = $ this ->getFdFromProxyMethod ($ name , $ arguments );
55-
5681 $ result = $ this ->check ($ fd );
5782 if ($ result ) {
5883 /** @var \Swoole\WebSocket\Server $server */
@@ -80,7 +105,16 @@ public function check($fd): bool
80105 return false ;
81106 }
82107
83- protected function getFdFromProxyMethod (string $ method , array $ arguments ): int
108+ public function setResponse (int $ fd , ?Response $ response ): void
109+ {
110+ if ($ response === null ) {
111+ unset($ this ->responses [$ fd ]);
112+ } else {
113+ $ this ->responses [$ fd ] = $ response ;
114+ }
115+ }
116+
117+ public function getFdFromProxyMethod (string $ method , array $ arguments ): int
84118 {
85119 if (! in_array ($ method , ['push ' , 'send ' , 'sendto ' ])) {
86120 throw new InvalidMethodException (sprintf ('Method [%s] is not allowed. ' , $ method ));
0 commit comments