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

  • Home
  • SEARCH
  • 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 8240513
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T20:30:53+00:00 2026-06-07T20:30:53+00:00

I’m trying to create a PHP client to connect to a simple java server,

  • 0

I’m trying to create a PHP client to connect to a simple java server, send some data, and receive a response back. The java server responds fine when interacting with a simple client coded in Java, but once a request is sent from a PHP client it hangs indefinitely when socket_read() is called. If this line is commented out the data arrives just fine, but when its not it doesnt seem as though the Java server receives the data at all. This is very similar to this previously asked question: Simple Java TCP Server and PHP Client Problems but as far as I can tell my code is nearly identical in operation to the solution given.

The java server is multithreaded, that is for other parts of the program and I dont beleive that is causing the issue. The php script has a UI hooked into it for testing. Anyone know whats going on?

Java Server:

    import java.io.*;
    import java.net.*;
    import java.lang.*;

    class TCPRelayServer
    {
        String clientSentence;
        String responseString;
        ServerSocket socket;
        Socket connection;

       public void TCPRelayServer() throws Exception{
             System.out.println("Created Relay");
        }

        public void run() throws Exception{            
                clientSentence = "";
                responseString = "";
                // Open socket to all localhost connections on port
                socket = new ServerSocket(9090, 100, InetAddress.getByName(null));
                socket.setSoTimeout(5000);

             while(true)
             {
                try{
                    System.out.println("**Relay Server**  Relay Server Waiting");

                    // Setup buffers and connection
                    connection = socket.accept();
                    InputStreamReader inputStream = new InputStreamReader(connection.getInputStream());
                    BufferedReader input = new BufferedReader(inputStream);
                    DataOutputStream response = new DataOutputStream(connection.getOutputStream());

                    // Get server input
                    clientSentence = input.readLine();
                    System.out.println("**Relay Server**  Received: " + clientSentence);

                    // Perform logic
                    responseString = clientSentence.toUpperCase() + "\n";

                    // send response
                    response.writeBytes("IT WORKED!\n");
                    response.flush();
                    response.close();

                }
                catch(Exception e){
                    continue;
                }
             }
        }
    }

    class Relay implements Runnable {

        Thread runner;
        public Relay() {
        }
        public Relay(String threadName) {
            runner = new Thread(this, threadName); // (1) Create a new thread.
            System.out.println(runner.getName());
            runner.start(); // (2) Start the thread.
        }
        public void run(){
            //Display info about this particular thread
            System.out.println("Thread Started: " + Thread.currentThread());

            TCPRelayServer relay = new TCPRelayServer();
            try{
                relay.run();
            }
            catch(Exception e){
                System.out.println("Relay Server Failed to Run");
                return;
            }
        }
    }

    public class Triplestore {

        public static void main(String[] args) {
            Relay RELAY = new Relay("Relay");
            //Server SERVER = new Server("Server");
            //Client CLIENT = new Client("Client");

            //Display info about the main thread
            System.out.println("Main Thread: " + Thread.currentThread());

            while(true){

            }
        }
    }

PHP Client:

<html>
    <head>
    <style type="text/css">

    input, textarea, label, div, a, form {
        display:inline;
        float:left;
        clear:left;
    }
    #messageLabel{
        clear:left;
        margin-top:20px;
    }
    form{
        width:600px;
    }
    textarea, input{
        font-size:14px;
        margin-left:30px;
    }
    input{
        padding:3px;
    }
    textarea{
        width:500px;
        height:300px;
        padding:10px;
    }
    input[type=submit]{
        float:right;
        margin-right: 70px;
        margin-top: 10px;
    }
    #results{
        font-family: monospace;
        clear: none;
        padding: 20px;
        background-color: black;
        color: white;
        margin-top: 30px;
        height: 299px;
        width: 500px;
        border: 3px solid #CCC;
        overflow:auto;
    }
    #results .success{color:#3ba13d;}
    #results .error{color:#c2291a;}


    </style>


    </head>
    <body>
        <form action="/test/tcp/tcp.php" method="post">
            <label for="port">Port Number: </label>
            <input type="text" name="port" id="port" value="9090"><br>

            <label for="message" id="messageLabel">Message: </label>
            <textarea placeholder="Type Message Here" id="message" name="message"></textarea><br>
            <input type="submit">
        </form>

        <div id="results">     
        <?php
            if(isset($_POST['port']) && isset($_POST['message'])){

                // Get port by service name or by port number
                $port = $_POST['port']; //getservbyname('www', 'tcp');

                // Get the IP address for the target hostname or by ip. 
                $address = '127.0.0.1'; //gethostbyname('localhost');

                // Get user message
                $message = $_POST['message'];
                $output = '';
                $next = '';


                // Create a TCP/IP socket.
                echo "Creating TCP/IP socket...";
                $socket = @socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
                //SOL_TCP
                if ($socket === false) {
                    echo "<br>&nbsp;&nbsp;&nbsp;<span class='error'><br>&nbsp;&nbsp;&nbsp; FAILED Reason: socket_create() - " . socket_strerror(socket_last_error()) . "<br></span>";
                } else {
                    echo "<br>&nbsp;&nbsp;&nbsp;<span class='success'>OK</span><br>";
                }

                // Connect to address on port
                echo "Connecting to '$address' on port '$service_port'...";
                $connect = @socket_connect($socket, $address, $port);
                if ($connect === false) {
                    echo "<br>&nbsp;&nbsp;&nbsp;<span class='error'>FAILED <br>&nbsp;&nbsp;&nbsp;Reason: socket_connect() - " . socket_strerror(socket_last_error($socket)) . "<br></span>";
                } else {
                    echo "<br>&nbsp;&nbsp;&nbsp;<span class='success'>OK</span><br>";
                }


                // Send Message
                echo "Sending message...";
                $sent = @socket_sendto($socket, $message, strlen($message), MSG_EOF, $address, $port);
                if ($sent === false) {
                    echo "<br>&nbsp;&nbsp;&nbsp;<span class='error'>FAILED<br>&nbsp;&nbsp;&nbsp;Reason: socket_write() - " . socket_strerror(socket_last_error($socket)) . "<br></span>";
                } else {
                    echo "<br>&nbsp;&nbsp;&nbsp;<span class='success'>OK</span><br>";
                }

                // Read Response
                echo "Reading response...<br>";

                //$line = socket_read($socket, 1024, PHP_NORMAL_READ);
                //$output .= $line;


                while($next = socket_read($socket, 4096, PHP_NORMAL_READ)){
                    $output .= $str;
                    if($next == "" || strpos($output,"\n") !== false)
                        break;
                }

                echo 'Output: ' . $output;
                if ($output === false) {
                    echo "<br>&nbsp;&nbsp;&nbsp;<span class='error'>FAILED <br>&nbsp;&nbsp;&nbsp;Reason: socket_read() - " . socket_strerror(socket_last_error($socket)) . "<br></span>";
                } else {
                    echo "&nbsp;&nbsp;&nbsp;" . $output . "<br>";
                }

                // Close Socket
                echo "Closing socket...";
                socket_close($socket);
                echo "<br>&nbsp;&nbsp;&nbsp;<span class='success'>OK</span><br>";
            }
            else{
                echo "Please enter a port number and message.<br>";
            }
        ?>
        </div>
    </body>

</html>
  • 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-06-07T20:30:55+00:00Added an answer on June 7, 2026 at 8:30 pm

    you use readline() in java, which blocks until it finds a new line. I don’t think you ever send a new line terminated string in your php code. So, both your java and php code should be blocking indefinitely.

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

Sidebar

Related Questions

I'm trying to create an if statement in PHP that prevents a single post
Basically, what I'm trying to create is a page of div tags, each has
I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I have some data like this: 1 2 3 4 5 9 2 6
I am trying to understand how to use SyndicationItem to display feed which is
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I would like to count the length of a string with PHP. The string

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.