简体   繁体   中英

Communication failure between PHP and Java through socket

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM