简体   繁体   English

PHP和Java之间通过套接字的通信失败

[英]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. 我正在尝试通过PHP向正在运行的JAVA程序发送和接收信息。

The program is the knockknockserver . 该程序是kickknockserver

The PHP-code im using is this: 我使用的PHP代码是这样的:

$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! 理想情况下,交互是我连接到端口4444 ,然后Java服务器响应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). 我遇到的问题是,如果我先运行Java服务器,PHP脚本将无法绑定套接字(我猜是因为它已经在使用中)。

And sometimes the socket_accept just makes my browser jam, so I have to entirely restart it to get it working again. 有时socket_accept只会使我的浏览器卡住,因此我必须完全重新启动它才能使其再次运行。

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. 您引用的PHP代码适用于服务器。 A TCP connection has a server side and a client side. TCP连接具有服务器端和客户端。 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. 您正在使用socket_bind (一种PHP函数)将服务器套接字绑定到本地端口并开始等待传入连接。 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). 您想使用socket_connect($socket, $address, $service_port)将客户端套接字连接到另一个已经运行的服务器(在您的情况下为Java Server)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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