0
我正在嘗試建立一個我正在與Java程序進行通信的網站。我對任何形式的套接字都很陌生,所以我遇到了問題,讓我的Java程序向我的網站發送迴應。這裏是我當前的Java代碼:Java和PHP套接字通信問題
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程序的響應。
另外我很確定我寫這個系統效率低下,錯誤。寫這種類型的系統的正確方法是什麼?有小費嗎?謝謝你的閱讀。