我有两个类 X 和 Y,如下所示:
class X implements Serializable
{
int val1;
Y val2;
}
class Y implements Serializable
{
int val;
}
我想将 X 类型的对象从客户端传输到服务器,但我不能,因为 X 类有一个 Y 类型的字段。我用 X 类中的 X 类型的字段替换了 Y 类型的字段,并且它有效。
编辑 这些是我的类(class):
class Y implements Serializable
{
int val;
Y()
{
val = 3;
}
}
class X implements Serializable
{
int val;
Y ob;
X(int i, Y o)
{
val = i;
ob = o;
}
}
public class Server
{
public static void main(String[] s)
{
ServerSocket ss = null;
Socket cs = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try
{
ss = new ServerSocket(1234);
System.out.println("Server pornit!");
cs = ss.accept();
oos = new ObjectOutputStream(cs.getOutputStream());
ois = new ObjectInputStream(cs.getInputStream());
}
catch(Exception e)
{
System.out.println("Exceptie!");
}
System.out.println("Asteapta mesaj...");
X x;
try
{
x = (X) ois.readObject();
System.out.println(x.val);
}
catch(Exception e)
{
System.out.println(e.toString());
}
try
{
ss.close();
cs.close();
}
catch(Exception e)
{
}
}
}
public class Client
{
public static void main(String[] s)
{
Socket cs;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
System.out.println("Connect...");
try
{
cs = new Socket("127.0.0.1",1234);
oos = new ObjectOutputStream(cs.getOutputStream());
ois = new ObjectInputStream(cs.getInputStream());
}
catch(Exception e)
{
System.out.println("Exceptie!");
}
try
{
oos.writeObject(new X(8,new Y()));
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
最佳答案
好的,我想我找到了问题所在。客户端进程在关闭输出流之前提前终止。结果,服务器意外断开连接。将 oos.close() 添加到客户端代码。
关于Java序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2694589/