1

I am trying to make a simple TCP/IP connection to a given IP and Port using sockets in PHP.

I am getting an error message that says "A non-blocking socket operation could not be completed immediately." below is my code:

<?php
$address = 'myhost.com';
$service_port = 1234;
$timeout = 1000;

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_nonblock($socket);
$error = NULL;
$attempts = 0;
while (!($connected = @socket_connect($socket, $address, $service_port)) && ($attempts < $timeout)) {
    $error = socket_last_error();
    if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
          echo socket_strerror($error) . "\n";
          socket_close($socket);
          return NULL;
    }
    usleep(1000);
    $attempts++;
}
?>

any ideas? i know there are no issues with the target host ip or port.

2 Answers 2

2

You are calling connect() on a non-blocking socket. The connect() call will always need to block to complete its operation, and since you explicitly told the socket to be non-blocking it immediately returns with an error telling you that it did not (yet) complete its operation.

You are a bit at the mercy of the OS you are using when using sockets directly. The code looks good overall. You will retry the connect until you get EINPROGRESS. Is that indeed the error code you are seeing? Maybe you are checking for the wrong error code?

Anyway your code looks to me like you try to connect until the connection is established. You can use blocking mode directly to achieve that.

Just leave the socket as blocking until you connected it and set the socket to non-blocking (assuming you really need that) after it is connected.

Sign up to request clarification or add additional context in comments.

Comments

2

non-blocking socket usually used for servers, servers are waiting for connection, so instead of using socket_connect, try using socket_listen instead

if you want to establish a connection to a server (be a client) then use Johannes's suggestion

1 Comment

i should have specified that i am indeed trying to connect to a server. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.