5
5
use Aternos \Taskmaster \Communication \MessageInterface ;
6
6
use Aternos \Taskmaster \Communication \Socket \Exception \SocketReadException ;
7
7
use Aternos \Taskmaster \Communication \Socket \Exception \SocketWriteException ;
8
+ use Aternos \Taskmaster \Taskmaster ;
8
9
use Generator ;
9
10
10
11
/**
@@ -22,6 +23,8 @@ class Socket implements SocketInterface, SelectableSocketInterface
22
23
*/
23
24
protected mixed $ socket ;
24
25
26
+ protected string $ receiveBuffer = "" ;
27
+
25
28
/**
26
29
* @param resource|Socket $socket
27
30
*/
@@ -62,10 +65,23 @@ public function receiveRaw(): Generator
62
65
if (!is_resource ($ this ->socket ) || feof ($ this ->socket )) {
63
66
throw new SocketReadException ("Could not read from socket. " );
64
67
}
65
- $ result = fgets ($ this ->socket );
68
+ $ result = $ this ->receiveBuffer ;
69
+ do {
70
+ $ chunk = fgets ($ this ->socket , 10_001 );
71
+ if ($ chunk === false || strlen ($ chunk ) === 0 ) {
72
+ break ;
73
+ }
74
+
75
+ $ result .= $ chunk ;
76
+ } while (!str_ends_with ($ result , PHP_EOL ));
66
77
if (!$ result ) {
67
78
break ;
68
79
}
80
+ if (!str_ends_with ($ result , PHP_EOL )) {
81
+ $ this ->receiveBuffer = $ result ;
82
+ break ;
83
+ }
84
+ $ this ->receiveBuffer = "" ;
69
85
$ decoded = base64_decode ($ result );
70
86
yield $ decoded ;
71
87
} while (true );
@@ -102,18 +118,22 @@ public function sendRaw(string $data): bool
102
118
}
103
119
$ data = base64_encode ($ data );
104
120
$ data .= PHP_EOL ;
105
- $ total = 0 ;
106
- $ expected = strlen ($ data );
121
+ $ current = 0 ;
122
+ $ total = strlen ($ data );
107
123
do {
108
124
if (!is_resource ($ this ->socket ) || feof ($ this ->socket )) {
109
125
throw new SocketWriteException ("Could not write to socket. " );
110
126
}
111
- $ result = @fwrite ($ this ->socket , $ data );
112
- if ($ result === false || $ result === 0 ) {
127
+ $ chunk = substr ($ data , $ current , 10_000 );
128
+ $ result = @fwrite ($ this ->socket , $ chunk );
129
+ if ($ result === false ) {
113
130
throw new SocketWriteException ("Could not write to socket. " );
114
131
}
115
- $ total += $ result ;
116
- } while ($ total < $ expected );
132
+ if ($ result === 0 ) {
133
+ usleep (Taskmaster::SOCKET_WAIT_TIME );
134
+ }
135
+ $ current += $ result ;
136
+ } while ($ current < $ total );
117
137
return true ;
118
138
}
119
139
0 commit comments