Skip to content

Commit a4ee9b1

Browse files
committed
Repair: socket::connect
1 parent c271615 commit a4ee9b1

File tree

1 file changed

+16
-32
lines changed

1 file changed

+16
-32
lines changed

src/Socket.php

Lines changed: 16 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -141,39 +141,23 @@ public static function connectWithSSL(string $address, int $timeout = 0, mixed $
141141
public static function connect(string $address, int $timeout = 0, mixed $context = null): Socket
142142
{
143143
try {
144-
return promise(static function (Closure $resolve, Closure $reject) use ($address, $timeout, $context) {
145-
$connection = @stream_socket_client(
146-
$address,
147-
$_,
148-
$_,
149-
$timeout,
150-
STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_CONNECT,
151-
$context
152-
);
153-
154-
if (!$connection) {
155-
$reject(new ConnectionException('Failed to connect to the server.', ConnectionException::CONNECTION_ERROR));
156-
return;
157-
}
158-
159-
$stream = new static($connection, $address);
160-
161-
if ($timeout > 0) {
162-
$timeoutEventID = delay(static function () use ($stream, $reject) {
163-
$stream->close();
164-
$reject(new ConnectionException('Connection timeout.', ConnectionException::CONNECTION_TIMEOUT));
165-
}, $timeout);
166-
$timeoutEventCancel = fn () => cancel($timeoutEventID);
167-
} else {
168-
$timeoutEventCancel = fn () => null;
169-
}
144+
$connection = @stream_socket_client(
145+
$address,
146+
$_,
147+
$_,
148+
$timeout,
149+
STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_CONNECT,
150+
$context
151+
);
152+
153+
if (!$connection) {
154+
throw (new ConnectionException('Failed to connect to the server.', ConnectionException::CONNECTION_ERROR));
155+
}
170156

171-
$stream->onWriteable(static function (Socket $stream, Closure $cancel) use ($resolve, $timeoutEventCancel) {
172-
$cancel();
173-
$resolve($stream);
174-
$timeoutEventCancel();
175-
});
176-
})->await();
157+
$stream = new static($connection, $address);
158+
$stream->waitForWriteable($timeout);
159+
$stream->cancelWriteable();
160+
return $stream;
177161
} catch (Throwable $exception) {
178162
throw new ConnectionException('Failed to connect to the server.', ConnectionException::CONNECTION_ERROR, $exception);
179163
}

0 commit comments

Comments
 (0)