note 130528 added to function.stream-socket-client

From: Date: Wed, 22 Oct 2025 21:00:08 +0000
Subject: note 130528 added to function.stream-socket-client
Groups: php.notes 
Request: Send a blank email to php-notes+get-222396@lists.php.net to get a copy of this message
<?php STREAM_CLIENT_ASYNC_CONNECT ?> opens a non-blocking socket (contradictory to the default blocking mode described in the manual page). You will have to check for its status using <?php stream_select ?> followed by <?php socket_import_stream ?> and <?php socket_get_option($socket, SOL_SOCKET, SO_ERROR) ?> You wouldn't normally do this, but when you do, you're more or less using glibc multisocket patterns. Here's a minimal example: <?php // open a "server" on port 7238 in a separate terminal (don't open it if you want to see the error path) // Netcat: nc -l 7238 // Socat: socat TCP-LISTEN:7238,fork,reuseaddr STDIO $stream = stream_socket_client("tcp://127.0.0.1:7238", $errno, $errstr, flags: STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT); while (true) { $w = [$stream]; $r = $e = []; $changed = stream_select($r, $w, $e, 1, 0); // if $changed is false, there's an error that I'm not handling here if (in_array($stream, $w)) { break; } } $socket = socket_import_stream($stream); $so_error = socket_get_option($socket, SOL_SOCKET, SO_ERROR); if ($so_error === 0) { fwrite($stream, "Hello!\n"); } else { // you'll have to look up the constant in <errno.h> // for example, 111 is ECONNREFUSED echo "There's been an error: errno=$so_error\n"; } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.137 (proxied: 2a02:6b67:e540:ad00:504d:824e:7a40:d21c) ---- Manual Page -- https://php.net/manual/en/function.stream-socket-client.php Edit -- https://main.php.net/note/edit/130528 Del: integrated -- https://main.php.net/note/delete/130528/integrated Del: useless -- https://main.php.net/note/delete/130528/useless Del: bad code -- https://main.php.net/note/delete/130528/bad+code Del: spam -- https://main.php.net/note/delete/130528/spam Del: non-english -- https://main.php.net/note/delete/130528/non-english Del: in docs -- https://main.php.net/note/delete/130528/in+docs Del: other reasons-- https://main.php.net/note/delete/130528 Reject -- https://main.php.net/note/reject/130528 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#222396) next »