我的问题是我有一个对象类(数据包),其中包含另一个对象(msg)。我让这两个类实现了Serializable 。但是当我运行我的程序时,我看到这个错误“java.io.StreamCorruptedException:invalid type code:00”我的代码的某些部分:
outStrm=new ObjectOutputStream(mySocket.getOutputStream());
inStrm=new ObjectInputStream(mySocket.getInputStream());
outStrm.writeObject(new packet());
outStrm.flush();
在服务器端我像这样阅读
Socket client = listen_socket.accept();
in=new ObjectInputStream(client.getInputStream());
out=new ObjectOutputStream(client.getOutputStream());
p=(packet) in.readObject();
我发送了很多数据包,奇怪的部分是当我调试它时(一步一步)我不会看到错误但是当我运行它时我有这个错误!请帮我。
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
class ServerThre
extends Thread
{
Socket client;
ObjectInputStream in;
ObjectOutputStream out;
public ServerThre(Socket client_socket)
{
client = client_socket;
try
{
in = new ObjectInputStream(client.getInputStream());
out = new ObjectOutputStream(client.getOutputStream());
}
catch (IOException e)
{
try
{
client.close();
}
catch (IOException e2)
{
}
System.err.println("Exception while getting input streams: " + e);
return;
}
this.start();
}
private packet getPacket() throws IOException
{
packet p;
try
{
p = (packet)in.readObject();
if (p != null)
{
return p;
}
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
return null;
}
@Override
public void run()
{
while (!client.isClosed())
{
packet p = null;
try
{
p = getPacket();
}
catch (IOException e1)
{
e1.printStackTrace();
}
if (p == null)
{
System.out.print("Connection closed by server, exiting");
return;
}
}// end of while
}
}
答案 0 :(得分:0)
此代码中有几个奇怪的地方。
p != null
中getPacket()
的测试完全毫无意义。
将p == null
等同于关闭连接的后续测试不正确。在这种情况下你会得到一个EOFException,而不是null。
Socket.isClosed()只会告诉您你是否关闭了套接字。