0

I have an issue when running PHP Client sending data to Java Server, the problem is Java server didnt show any input stream from PHP Client.

Java server output only show "Just connected.." when i execute php client, i'm expecting it shows "Testing" , here's java code :

Waiting for client on port 3000...
Waiting for client on port 3000...
Waiting for client on port 3000...
Waiting for client on port 3000...
Just connected to /127.0.0.1:39220
Waiting for client on port 3000...

PHP Client Output :

$ sudo php testSocketClient.php
Try to connect '127.0.0.1' Port '3000'...
Connect OK
Send Message to Server Successfully!
Send Information:Testing

Turn Off Socket...
Turn Off OK

Here's my PHP Client code, this is where i send "Testing" message :

<?php
set_time_limit(0);

$port = 3000;
$ip   = "127.0.0.1";

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if($socket < 0) {
    echo "socket_create() Fail to create:".socket_strerror($sock)."\n";
} else {
    echo "Try to connect '$ip' Port '$port'...\n";
    $result = socket_connect($socket, $ip, $port);
    if ($result < 0) {
        echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
    }else {
        echo "Connect OK\n";

        $in = "Testing\r\n";
        $out = '';

        if(!socket_write($socket, $in, strlen($in))) {
            echo "socket_write() failed. reason: " . socket_strerror($socket) . "\n";
        }else {
            echo "Send Message to Server Successfully!\n";
            echo "Send Information:" . $in . "\n";

            echo "Turn Off Socket...\n";
            socket_close($socket);
            echo "Turn Off OK\n";
        }
    }
}

This is my Java Server Code :

package TestPackage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

public class TestSocketListener {
    public static void main(String[] args) {
        System.out.println("INIT SOCKET");
        int port = 3000;
        while(true) {
            try {
                ServerSocket serverSocket = new ServerSocket(port);
                serverSocket.setSoTimeout(5000);

                System.out.println("Waiting for client on port " +
                        serverSocket.getLocalPort() + "...");
                Socket server = serverSocket.accept();

                System.out.println("Just connected to " + server.getRemoteSocketAddress());
                DataInputStream DataInStream = new DataInputStream(server.getInputStream());

                System.out.println(DataInStream.readUTF());
                DataOutputStream DataOutStream = new DataOutputStream(server.getOutputStream());
                DataOutStream.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
                        + "\nGoodbye!");
                server.close();

                System.out.println(("SERVER CLOSED"));
            } catch(SocketTimeoutException st) {
                //System.out.println("Socket timed out!");
            } catch(SocketException s) {
                //System.out.println("Socket Error!!");
                //s.getMessage();
            } catch (IOException e) {
                //System.out.println("IO Error!");
            }
        }
    }
}

This is error message when using exception (same error occured when trying to use different port. i'm trying 3000, 4444, and 29299):

java.net.BindException: Address already in use (Bind failed)
        at java.net.PlainSocketImpl.socketBind(Native Method)
        at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
        at java.net.ServerSocket.bind(ServerSocket.java:375)
        at java.net.ServerSocket.<init>(ServerSocket.java:237)
        at java.net.ServerSocket.<init>(ServerSocket.java:128)
        at TestPackage.TestSocketListener.main(TestSocketListener.java:17)

Currently port used :

$ nmap 127.0.0.1
Starting Nmap 6.40 ( http://nmap.org ) at 2019-08-01 17:32 WIB
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00046s latency).
Not shown: 994 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
25/tcp   open  smtp
80/tcp   open  http
111/tcp  open  rpcbind
443/tcp  open  https
3306/tcp open  mysql
4
  • You are completely ignoring the caught exceptions, consider printing their message . Commented Aug 1, 2019 at 10:15
  • I'm updating the thread, it shows something like Bind Failed Commented Aug 1, 2019 at 10:23
  • This error shows that another application is already listening on this port. Check that you don't have some other instance of TestSocketListener running, or which application is currently using this port. Commented Aug 1, 2019 at 10:25
  • I'm using port 3000, 4444, and 29299 and its still having same error. i'm pretty sure no application using this port, i'm adding nmap result (port scan) Commented Aug 1, 2019 at 10:30

1 Answer 1

1

I got it to work. According to the JAVA documentation, an IOException can occur if the client closes the connection. See: DataInputStream. Your PHP code executes and ends the connection. But this is still not a problem with your PHP code. You are using the readUTF() method which doesn't really tell JAVA how many bytes to read; it's not reliable. Instead, use read([]byte b, int off, int len)

Here is my output:

INIT SOCKET
Waiting for client on port 3000...
Just connected to /127.0.0.1:61989
Testing

SERVER CLOSED

Here is the code change:

package TestPackage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.channels.IllegalBlockingModeException;

public class TestSocketListener {
    public static void main(String[] args) {
        System.out.println("INIT SOCKET");
        int port = 3000;
        while(true) {
            try {
                ServerSocket serverSocket = new ServerSocket(port);
                serverSocket.setSoTimeout(5000);

                System.out.println("Waiting for client on port " +
                        serverSocket.getLocalPort() + "...");
                Socket server = serverSocket.accept();

                System.out.println("Just connected to " + server.getRemoteSocketAddress());

                // you want to know how much bytes to read
                InputStream inputstream = server.getInputStream();
                int buflen = inputstream.available();

                DataInputStream DataInStream = new DataInputStream(inputstream);

                byte[] rawstring = new byte[buflen];
                DataInStream.read(rawstring, 0, buflen);
                String str = new String(rawstring);
                System.out.println(str);

                DataOutputStream DataOutStream = new DataOutputStream(server.getOutputStream());
                DataOutStream.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
                        + "\nGoodbye!");
                server.close();

                System.out.println(("SERVER CLOSED"));
            } catch(SocketTimeoutException st) {
                System.out.println("Socket timed out!");
            } catch(SocketException s) {
                //System.out.println("Socket Error!!");
                //s.getMessage();
            } catch (IOException e) {
                //System.out.println("IO Error!");
            }
        }
    }
}

Hope this helps!

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

Comments

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.