我正在使用 php 编写套接字客户端,并且我想将字符串消息发布到由 java 实现的套接字服务器,但是我们尝试从 php 套接字客户端发布数据,java 套接字服务器因 java.io.StreamCorruptedException 异常而崩溃. 以下是我的 PHP 套接字客户端、Java 套接字服务器的代码以及我发布消息时引发的错误。
$fp = fsockopen("127.0.0.1", 1080, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "hello";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
爪哇代码
providerSocket = new ServerSocket(1080, 10);
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
try{
message = (String)in.readObject();
System.out.println("client>" + message);
}
catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
}
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
providerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
我得到的错误
java.io.StreamCorruptedException: invalid stream header: 48656C6C
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Provider.run(Provider.java:37)
at Provider.main(Provider.java:109)
Exception in thread "main" java.lang.NullPointerException
at Provider.run(Provider.java:85)
at Provider.main(Provider.java:109)