[英]simple client server communication between java and php
我需要從php客戶端發送信息到java服務器,但是沒有一個在服務器端接收,雖然在服務器上成功執行了一個print語句,客戶端的文本無法在服務器端接收。 以下是代碼:
Java服務器:
import java.io.BufferedReader;
import java.net.*;
import java.io.*;
public class javaphp2 {
private static ServerSocket socket;
private static Socket connection;
private static String command = new String();
private static String responseStr = new String();
private static int port = 4309;
public static void main(String args[]) {
System.out.println("Signal Server is running.");
try {
socket = new ServerSocket(port);
while (true) {
connection = socket.accept();
InputStreamReader inputStream = new InputStreamReader(connection.getInputStream());
DataOutputStream response = new DataOutputStream(connection.getOutputStream());
BufferedReader input = new BufferedReader(inputStream);
command = input.readLine();
//System.out.println("The input is" + command);
response.writeBytes(responseStr);
response.flush();
//response.close();
System.out.println("Running");
}
} catch (IOException e) {
System.out.println("Fail!: " + e.toString());
}
System.out.println("Closing...");
}
}
PHP客戶端:
#!/usr/local/bin/php -q
<?php
$address = '132.119.90.165';
$port = 4309;
$socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_connect($socket, $address, $port);
$message = 'Apple';
$len = strlen($message);
$status = socket_sendto($socket, $message, $len, 0, $address, $port);
if($status !== FALSE)
{
$message = '';
$next = '';
while ($next = socket_read($socket, 4096))
{
$message .= $next;
}
echo $message;
}
else
{
echo "Failed";
}
socket_close($socket);
?>
得到它了 !,
我們需要添加$message = "Apple\\n";
而不是$message = 'Apple\\n';
嘗試在郵件中添加行尾。
$message = 'Apple\n';
readLine將始終等待行結束。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.