我正在尝试让我正在开发的网站与Java程序进行通信。我对任何形式的套接字都很陌生,所以我在让Java程序将响应发送回我的网站时遇到了问题。这是我当前的Java代码:
while(true) {
ServerSocket socket = null;
Socket connection = null;
InputStreamReader inputStream = null;
BufferedReader input = null;
DataOutputStream response = null;
System.out.println("Server running");
try {
socket = new ServerSocket(4400);
while(true) {
connection = socket.accept();
inputStream = new InputStreamReader(connection.getInputStream());
input = new BufferedReader(inputStream);
String command = input.readLine();
System.out.println("command: " + command);
if(command.equals("restart")) {
break;
} else if(command.equals("requeststatus")) {
String reply = "testing";
System.out.println(reply);
response = new DataOutputStream(connection.getOutputStream());
response.writeUTF(reply);
response.flush();
}
}
} catch(IOException e) {
e.printStackTrace();
} finally {
if(socket != null) {
try {
socket.close();
} catch(IOException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch(IOException e) {
e.printStackTrace();
}
}
if(inputStream != null) {
try {
inputStream.close();
} catch(IOException e) {
e.printStackTrace();
}
}
if(input != null) {
try {
input.close();
} catch(IOException e) {
e.printStackTrace();
}
}
if(response != null) {
try {
response.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Server Closing");
}
我目前的PHP代码:
<?php
function send($message) {
$address = 'localhost';
$port = 4400;
$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
try {
socket_connect($socket, $address, $port);
$status = socket_sendto($socket, $message, strlen($message), MSG_EOF, $address, $port);
if($status != false) {
// If it worked then wait for a response?
// This is where the problem is at
if($next = socket_read($socket, $port)) {
echo $next;
}
return true;
}
return false;
} catch(Exception $e) {
return false;
}
}
if(send("requeststatus")) {
echo "Worked";
}
?>
当我启动程序并加载网页时,页面会不断加载,而不会打印任何内容。我猜PHP运行所有内容,然后在脚本完成后在我的浏览器中显示结果,而我的脚本在等待回复时被"阻塞"了?如果是这样的话,我该如何让我的PHP脚本向我的Java程序发送"requeststatus",并让Java程序做出响应?最终目标是在我的网站上显示Java程序的响应。
此外,我确信我写这个系统的效率很低,而且是错误的。编写这种类型的系统的正确方法是什么?有什么建议吗?感谢您的阅读。
String command = input.readLine();
这将等待换行或流的结束。您从不发送换行符,如果关闭流,也不能写入输出。
所以基本上在你的信息中添加一行换行符。