我在将数据从 PHP 脚本发送到 Java 守护程序时遇到一些问题。
这是 Java:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Listener implements Runnable {
ServerSocket listenerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
@Override
public void run()
{
try{
listenerSocket = new ServerSocket(7331);
System.out.println("Waiting for connection");
connection = listenerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
do{
try{
message = (String)in.readObject();
System.out.println("client>" + message);
}
catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
}
}while(!message.equals("bye"));
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
try{
in.close();
out.close();
listenerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
}
这是 PHP 代码:
<?php
header('Content-Type: text/html; charset=utf-8');
$fp = fsockopen("127.0.0.1", 7331, $errno, $errstr);
if (!$fp) {
echo "ERROR: $errno - $errstr<br />\n";
} else {
fwrite($fp, "yaydata");
echo fread($fp, 26);
fclose($fp);
}
?>
这是我在 Java 中遇到的错误:
Waiting for connection
Connection received from localhost.localdomain
java.io.StreamCorruptedException: invalid stream header: 6675636B
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at com.cj.panel.Listener.run(Listener.java:25)
at java.lang.Thread.run(Thread.java:744)
Exception in thread "Thread-0" java.lang.NullPointerException
at com.cj.panel.Listener.run(Listener.java:41)
at java.lang.Thread.run(Thread.java:744)
我似乎看不出这有什么问题。我对跨平台网络东西很陌生,因此感谢您的帮助。
最佳答案
ObjectInputStream
和 ObjectOutputStream
用于读取和写入序列化 Java 对象,并且仅在两个 Java 程序之间使用。您的 PHP 程序不知道如何以 ObjectInputStream
可以处理的形式编写任何内容。
您应该在 Java 程序中使用纯输入/输出流。
关于java - PHP 向 Java 守护进程发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20297276/