Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 543079
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T10:30:49+00:00 2026-05-13T10:30:49+00:00

I recently found out that PHP not only has the fsock* functions, but also

  • 0

I recently found out that PHP not only has the fsock* functions, but also functions to create a server itself. I decided to experiment a little bit, and came up with this. Now, the problem is that it hangs on accept_connection() (due to the fact that it’s waiting for a connection.) I found out that the solution is to use stream_set_blocking(), which as you can see, I attempted, but to no avail.

I am getting an error message, which reads:

Warning: socket_set_blocking(): supplied resource is not a valid stream resource in /home/insomniaque/workspace/PHP Socket RAT/rat.class.php on line 68

I know that accept_connection() was the problem earlier because when I would connect with a second connection, it would output the data.

<?php
/*
 * Project: iRAT
 * 
 * Created on Jan 11, 2010
 * Written by Insomniaque
 * 
 */

class rat
{
    /**
     * Holds the PHP socket handle for use within the class.
     */
    private $socket;

    /**
     * Holds an array of all the spawned sockets (child sockets) that were
     * created when a user connected to the server.
     */
    private $spawns = array ();

    /**
     * Holds the maximum number of connections.
     */
    private $maxconn;

    /**
     * Sets all of the variables required for the class and starts the socket.
     * Then it'll start looping, connecting clients and running commands.
     * 
     * @access public
     * @param $port The port to bind.
     * @param $maxconn The maximum number of client connections.
     */
    public function __construct($port = 0, $maxconn = 1)
    {
        /**
         * Check to see if the user has entered 0 as the port, and create a
         * random port, if so.
         */
        if($port == 0)
            $this->port = rand(81, 8079);
        else
            $this->port = $port;

        /**
         * Save the maximum connection number.
         */
        $this->maxconn = $maxconn;

        /**
         * Run our function to create the socket now.
         */
        if(!$this->createSocket())
        {
            echo "Failed creating or binding socket.\n";
            return false;
        }
        else
        {
            echo "Socket has been created and binded.\n";
        }

        /**
         * Turn non-blocking on so we can run multiple clients.
         */
        socket_set_blocking($this->socket, 0);

        echo "Starting the data receiving loop.\n";
        $this->startLoop();

        return true;
    }

    /**
     * This function will create the socket for later use.
     * 
     * @access private
     * @return bool Returns true if the socket was created successfully,
     *              returns false if there was an error.
     */
    private function createSocket()
    {
        /**
         * Create a socket of IPv4 type using the TCP gateway.
         */
        $this->socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
        if(!$this->socket)
            return false;
        echo "Socket has been created.\n";

        /**
         *  Attempt to bind the socket to localhost:[port]
         */
        do
        {
            if(!isset($i))
                $i++;

            $port = $this->port;
            $bind = socket_bind($this->socket, 0, $port);

            if(!$bind)
            {
                $i++;
                $this->port = rand(79, 8079);
            }
        } while(!$bind && $i <= 5);

        if($i == 5)
            return false;
        echo "Port ".$this->port." has been binded to the RAT.\n";

        return true;
    }

    /**
     * Start a loop running on our socket. We will check if we are getting
     * data, accept connections and run any commands. When the connection
     * is closed, we will return true.
     * 
     * @access private
     * @return bool Returns false if the socket can't be listened to. Otherwise
     *              returns true when the socket is closed.
     */
    private function startLoop()
    {
        if(socket_listen($this->socket, 3))
        {
            while(true)
            {   
                if(($newspawn = socket_accept($this->socket)) !== false)
                {
                    $this->spawns[] = $newspawn;
                    echo "A new spawn has connected.";
                } else
                    echo "No new socket";
                sleep(1000);

                foreach($this->spawns as $key => $spawn)
                {
                    $data = trim(socket_read($spawn, 1024));
                    if(strlen($data) > 0)
                    {
                        if($data == "exit")
                        {
                            socket_close($spawn);
                            unset($this->spawns[$key]);
                            echo "Spawn killed.\n";
                        }
                        if($data == "kill")
                        {
                            foreach($this->spawns as $key => $spawn)
                            {
                                socket_close($spawn);
                                unset($this->spawns[$key]);
                            }
                            socket_close($this->socket);
                            echo "Socket closed.\n";
                            return true;
                        }
                        else
                        {
                            echo "Data: " . $data . "\n";
                        }
                    }
                }
            }
        }
        else
        {
            echo "Failure receiving data.\n";
            return false;
        }
    }
}
?>

Thanks in advance,
John

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T10:30:49+00:00Added an answer on May 13, 2026 at 10:30 am

    Use socket_set_nonblock() instead of socket_set_blocking() for a socket resource create by socket_create().

    socket_set_blocking() is an alias for
    stream_set_blocking() which only works for (php-)streams, like the result of fopen() or stream_socket_create()

    edit: You can also use socket_select() or stream_select() to handle both new connections and client data packet, e.g.

    private function createSocket()
    {
      $this->socket = stream_socket_server('tcp://0.0.0.0:'.(int)$this->port, $errno, $errstr);
      if(!$this->socket) {
        $this->socket = null;
        echo "stream_socket_server failed : $errstr ($errno)\n";
        return false;
      }
      echo "Port ".$this->port." has been bound to the RAT.\n";
      return true;
    }
    
    public function startLoop() {
      if ( is_null($this->socket) ) {
        return false;
      }
    
      $write = array(); $exception=array();
      while( !$this->shutdown ) {
        // stream_select() alters the array, so $read has to be re-constructed in each iteration somehow
        $read = array_merge(array($this->socket), $this->spawns);
        // you might want to check $exception as well
        if ( 0!==stream_select($read, $write, $exception, 4) ) {
          // $now $read only contains those sockets, that will not block
          // for fread/accept operations
          foreach($read as $s) {
            if ( $s===$this->socket ) {
              $this->onAccept();
            }
            else {
              $this->onClientPacket($s);
            }
          }
        }
      }
      $this->shutdown();
    }
    

    Keep in mind that if a client sends two commands like e.g.

    $fp1 = stream_socket_client("tcp://localhost:81", $errno, $errstr, 30);
    fwrite($fp1, "1 blabla");
    fwrite($fp1, "exit");
    

    it doesn’t necessarily mean your server will get two separate messages.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 336k
  • Answers 336k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer This method assumes the words are only separated by spaces… May 14, 2026 at 3:45 am
  • Editorial Team
    Editorial Team added an answer To the best of my knowledge, there is none. Writing… May 14, 2026 at 3:45 am
  • Editorial Team
    Editorial Team added an answer Here is what I expect is going on: You keypress… May 14, 2026 at 3:45 am

Related Questions

I am using php and mysql. Each time a user registers on my website,
I have a script that checks responses from HTTP servers using the PEAR HTTP
This question is mainly geared towards Zend in PHP, although it certainly applies to
I recently found out that PHP 5.3 supports new language construct called GOTO .
I'm running PHP on Windows/IIS. My session variables don't seem to be preserved from

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.