我正在開展一個學校項目,下面的代碼是爲構建項目提供的示例(應該沒有任何問題但不能......)。有沒有編譯錯誤,但是當我使用telnet來測試它下面的消息顯示:ObjectInputStream和getInputStream
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=...
的順序,但沒有運氣。請幫助...謝謝。
你在這段代碼中做了什麼?不,你想做什麼? – Ankit 2013-04-10 04:39:52
您確定客戶端正在使用ObjectOutputStream編寫對象嗎? – 2013-04-10 04:43:27
您需要執行序列化。 – Hemanth 2013-04-10 04:51:24