0

Ok so i have a class that uses while(true) and it connects using a socket. Now my problem is that when i use socket_set_nonblock it doesn't connect it dies with "Could not connect.". When i put it after sending a packet, it goes from the start and re does everything.

Here is my connect function:

function connect($ip, $port) {
        if($this->soc!=null) socket_close($this->soc);
        $this->soc = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
        if(!$this->soc) die(socket_strerror(socket_last_error($this->soc)));
        if(!socket_connect($this->soc,$ip,$port)) die("Could not connect."); 

    }

Heres the function when attempting to use socket_set_nonblock

function connect($ip, $port) {
        if($this->soc!=null) socket_close($this->soc);
        $this->soc = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
        socket_set_nonblock($this->soc);
        if(!$this->soc) die(socket_strerror(socket_last_error($this->soc)));
        if(!socket_connect($this->soc,$ip,$port)) die("Could not connect."); 

    }
John Aoro
  • 29
  • 3
  • If you had looked at the PHP errors you would have seen that your question is a duplicate of: http://stackoverflow.com/q/6202454 – igorw Oct 27 '12 at 00:21
  • I did not understand that, can you please explain how i fix it? Plus that wasn't php – John Aoro Oct 27 '12 at 00:25

1 Answers1

0

First of all, you need to tell us why you want to put the socket in non-blocking mode. There are two main reasons for that:

  • To multiplex several file descriptors/sockets (depending on language/platform) on a single thread.
  • To set a timeout for operations.

Anyway, there are two phases to a non-blocking connect():

  • Initiate a connection. In php, done with socket_connect(), which will typically fail with SOCKET_EINPROGRESS; in which case you'll need phase two:
  • Wait for the connection to complete, and check the status. The waiting part is done with socket_select(), where you can multiplex several sockets you are waiting events for. When it returns, you need to iterate over the sockets it returns; when you get to a socket that is waiting for a successful connection, you check the result of the connection with socket_get_option($socket, SOL_SOCKET, SO_ERROR).
ninjalj
  • 42,493
  • 9
  • 106
  • 148