0

I've run into a problem, and I hope you guys might know where I'm going wrong.

I'm trying to send and receive information through PHP to my running JAVA program.

The program is the knockknockserver.

The PHP-code im using is this:

$host='127.0.0.1';
$port=4444;

$socket=socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not 
create socket \n");

$result=socket_bind($socket, $host, $port) or die("Could not bind to 
 socket\n");


$result=socket_listen($socket, 3) or die('Could not set up socket 
listenern');

$spawn=socket_accept($socket) or die('Could not accept incoming 
connection');

$input=socket_read($result, 1024) or die('Could not read input');

socket_close($spawn);
socket_close($socket);

I just grabbed from the net.

Ideally the interaction would be that I connect to the port 4444, then the Java server responds knock knock!.

The problem I'm having is that, if i run Java server first the PHP script fails to bind the socket (I'm guessing since it's already in use).

And sometimes the socket_accept just makes my browser jam, so I have to entirely restart it to get it working again.

What I'm really trying to do is learn how to communicate through ports, I've been trying to read, but I just don't understand why I cannot connect and accept communication through an already open port.

2
  • What's the error message? Could not bind to socket\n? Commented Jan 19, 2018 at 13:24
  • Yes, exactly if the Java server is going on the port I get that error, if the java server is off, I get could not read input. Commented Jan 19, 2018 at 13:29

1 Answer 1

1

The PHP code you are quoting is also for a server. A TCP connection has a server side and a client side. You can't magically make to servers 'talk' to eachother.

You are using socket_bind, a PHP function to bind the server socket to a local port and start waiting for incoming connections. You want to use socket_connect($socket, $address, $service_port) instead to connect a client socket to another, already running server (in your case the Java Server).

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

2 Comments

I see, I'm having some trouble reading the server output, do you know which socket commands are necessary to read? socket_create i guess would be the same, followed by socket connect, if i follow that up with a socket _read i get 'Could not read input' however.
@MarcusGrass If you have a new problem, you should ask a new question and not discuss further here in the comments. If this answer solved your problem, please accept the answer as correct. Thank you! :)

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.