get socket error string when async connect fails

ε祈祈猫儿з 提交于 2019-12-13 15:27:17

问题


anybody knows if its possible to retrieve some error info (like getsockopt SO_ERROR in C) if an async connect like the following fails btw: im not using the socket extension cause streams provide an ssl wrapper

<?php
$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
$destination = "tcp://92.247.12.242:8081";
$socket = stream_socket_client($destination, $errno, $errstr,
                                         10, STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT, $ctx);a
// plain socket
var_dump($socket);
// no error as expected
var_dump($errno);
var_dump($errstr);

stream_set_blocking($socket, false);

/* Prepare the read array */
$read   = array($socket);
$write  = array($socket);
$except = NULL;
if (false === ($num_changed_streams = stream_select($read, $write, $except, 10))) {
    var_dump("select failed?");
    /* Error handling */
} elseif ($num_changed_streams > 0) {

    /* At least on one of the streams something interesting happened */
    var_dump("event");
    // read fails, so the connect fails but why?
    $result = stream_socket_recvfrom($socket, 1024);
    var_dump($result);
    // no error again
    var_dump($errno);
    var_dump($errstr);
    // nothing interesting
    var_dump(stream_get_meta_data($socket));
}
// wont get called
function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
    $args = func_get_args();
    var_dump($args);
}

thx


回答1:


I'm having the same issue as described. I have found a bit of a workaround:

I wrap each of my 'streams' in a Stream class and set a timeout property. Before I call connect, I generate a timestamp of when the timeout should occur. I then have a loop in a Manager class which calls stream_select().

Successful connections are placed in the $write array. I have another call at the bottom of the loop that calls $stream->checkTimeout(). Within that there is a stream_select() call with 0 set for tv_sec and tv_usec. If $this->conn doesn't appear within $write, I assume it has timed out.




回答2:


As far as I understand errors in stream functions should generate PHP warning messages. I think the only way would be to trap these using set_error_handler() and process them there.




回答3:


I ran into this issue as well. Solution I found is to use stream_socket_get_name. If you want this all wrapped up in a nice library checkout http://drupal.org/project/httprl. It still requires drupal, but mainly for settings & error handling; you can modify the code a little bit and it should run on its own.



来源:https://stackoverflow.com/questions/3333398/get-socket-error-string-when-async-connect-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!