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 7010255
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T21:58:04+00:00 2026-05-27T21:58:04+00:00

I writing a command and then reading back from a server via sockets in

  • 0

I writing a command and then reading back from a server via sockets in PHP. We have 20 servers that all run a Node JS script which can receive these commands and execute them. The Node JS script will return “ok” which PHP reads back to confirm the command has gone through.

The Node JS script listens on port 9000 and is set to allow half open.

Most of the time this works fine, but when a high volume of commands are sent we get errors back occasionally that say this:

Contents: Message received back from socket was 'Unexpected token {'
Transport endpoint is not connected

The transport endpoint message suggests to me that it has not connected successfully.

I am no expert in sockets so I don’t know whether the implementation I have used is “correct”. It does work most of the time but I am aware that there are functions like socket_bind and socket_listen that may work better, though I am not sure what they do.

Here is the PHP code that we are using. Any suggestions would be most appreciated.

public function sendDaemonCommand($address, $template_id, $params = array()) {

    $hostname = $this->getHostnameFromPrivateIP($address);
    $port = 9000;
    $command = array('template_id' => $template_id, 'params' => $params);
    $command = json_encode($command);

    // Create a TCP Stream socket
    if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
        $this->mailError("Command Failed - " . $hostname, "Failed to create socket on " . $address . "\n\n" . socket_strerror(socket_last_error()) . "\n\nCommand:\n\n" . $command . "\n" . $this->functionTraceback());
        return false;
    }

    // Connect to socket
    if (socket_connect($sock, $address, $port) === false) {
        $this->mailError("Command Failed - " . $hostname, "Failed to connect to socket on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
        socket_close($sock);
        return false;
    }

    // Write command to socket
    $_command = $command;
    $length = strlen($_command);

    while (true) {
        $sent = socket_write($sock, $_command, $length);

        if ($sent === false) {
            $this->mailError("Command Failed - " . $hostname, "Failed to write command to socket on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
            socket_shutdown($sock, 2);
            socket_close($sock);
            return false;
        }

        if ($sent < $length) {
            $_command = substr($_command, $sent);
            $length -= $sent;
        }
        else {
            break;
        }
    }

    socket_shutdown($sock, 1);

    // Read back from socket
    if (($out = socket_read($sock, 1024)) !== false) {
        @socket_shutdown($sock, 0);
        $out = trim($out);
        if ($out !== "ok") {
            $this->mailError("Command Failed - " . $hostname, "Message received back from socket was '" . $out . "' on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
            socket_close($sock);
            return false;
        }
    }
    else {
        $this->mailError("Command Failed - " . $hostname, "Failed to read from socket on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
        socket_shutdown($sock, 0);
        socket_close($sock);
        return false;
    }

    socket_close($sock);
    return $out;
}
  • 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-27T21:58:04+00:00Added an answer on May 27, 2026 at 9:58 pm

    For a simple socket client such as this, I much prefer fsockopen() – it drastically reduces the complication of the client code and does not require the sockets extension, which is not available everywhere. The main disadvantage to this is that you lose the string error messages, but these are rarely that useful anyway – you still get an error string from creating the socket, and if read/write operations fail it’s because the socket has become disconnected.

    I’m also not sure how useful “allow half open” is in this context – I think it is likely to create more problems than it solves. The calls to socket_shutdown() are not doing anything useful here (and may be the source of your problems) – you would only use this if you are operating on a socket that will not be closed and may be operated on at a later point in time by some other code. Since you create a new socket and destroy it in the same routine, this is not the case.

    Here is your code rewritten to use fsockopen() – as you can see, it is somewhat shorter and simpler. I have also modified it slightly so that it always returns a bool – your code returns either bool FALSE or string ok, and since there are only these two options it makes more sense for the function to always return a bool.

    public function sendDaemonCommand($address, $template_id, $params = array()) {
    
        // Prepare data
        $hostname = $this->getHostnameFromPrivateIP($address);
        $port = 9000;
        $command = array('template_id' => $template_id, 'params' => $params);
        $_command = $command = json_encode($command);
        $length = strlen($_command);
    
        // Connect to socket
        if (!$sock = fsockopen($address, $port, $errNo, $errStr)) {
            $this->mailError("Command Failed - " . $hostname, "Failed to connect to socket on " . $address . "\n\n" . $errStr . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
            return false;
        }
    
        // Write command to socket
        while (true) {
    
            // Try and write data to socket
            $sent = fwrite($sock, $_command, $length);
    
            // If it failed, error out
            if ($sent === false) {
                $this->mailError("Command Failed - " . $hostname, "Failed to write command to socket on " . $address . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
                fclose($sock);
                return false;
            }
    
            // If there is data left to send, try again
            if ($sent < $length) {
                $_command = substr($_command, $sent);
                $length -= $sent;
                continue;
            }
    
            // If we get here the write operation was successful
            break;
    
        }
    
        // Read back from socket and close it
        $out = fread($sock, 1024);
        fclose($sock);
    
        // Test the response from the server
        if ($out === false) {
            $this->mailError("Command Failed - " . $hostname, "Failed to read from socket on " . $address . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
            return false;
        } else if (($out = trim($out)) !== "ok") {
            $this->mailError("Command Failed - " . $hostname, "Message received back from socket was '" . $out . "' on " . $address . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
            return false;
        } else {
            return true;
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm writing a .NET command-line application that will migrate users from an existing database
If you are writing a program that is executable from the command line, you
I'm writing in wpf. In my viewModel I have a command that opens new
I am writing a command-line tool for Windows that uses libcurl to download files
I'm writing a simple ruby sandbox command-line utility to copy and unzip directories from
I'm writing a Python application that takes a command as an argument, for example:
I'm writing a command-line tool for Mac OS X that processes a bunch of
I've written a command line tool that preprocesses a number of files then compiles
I have two inputs reading into my command prompt, the first being a series
I'm using a FileManager for a project so that reading and writing is less

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.