我正在开展一个学校项目,以下代码是为构建项目提供的示例(应该可以正常工作,但不是......)。没有编译错误,但是当我使用 telnet 对其进行测试时,显示以下消息:
java.io.StreamCorruptedException: invalid stream header: 56543130
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:801)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
at ThreadedDataObjectHandler.run(ThreadedDataObjectServer.java:41)
第 41 行是
ObjectInputStream in =new ObjectInputStream(incoming.getInputStream());
这是我的代码:
import java.io.*;
import java.net.*;
import java.util.*;
public class ThreadedDataObjectServer {
public static void main(String[] args ) {
try
{ ServerSocket s = new ServerSocket(3000);
for (;;)
{ Socket incoming = s.accept( );
new ThreadedDataObjectHandler(incoming).start();
}
}
catch (Exception e)
{ e.printStackTrace();
}
}
}
class ThreadedDataObjectHandler extends Thread
{
DataObject myObject = null;
private Socket incoming;
private String greeting="Hello!";
public ThreadedDataObjectHandler(Socket incoming)
{
this.incoming = incoming;
}
public void run()
{ try
{
ObjectInputStream in =new ObjectInputStream(incoming.getInputStream());
ObjectOutputStream out =new ObjectOutputStream(incoming.getOutputStream());
myObject = (DataObject)in.readObject();
System.out.println("Message read: " + myObject.getMessage());
myObject.setMessage("Got it!");
System.out.println("Message written: " + myObject.getMessage());
out.writeObject(myObject);
in.close();
out.close();
incoming.close();
}
catch (Exception e)
{ e.printStackTrace();
}
}
}
class DataObject implements Serializable{
protected String message;
public DataObject(){
message="";
}
public void setMessage(String m){
message=m;
}
public String getMessage(){
return message;
}
}
我尝试的是切换语句的顺序,ObjectInputStream in=...
但ObjectOutputStream out=...
没有运气。请帮助...谢谢。