这里我有两个类 ClientToSendCalculable.java
import java.io.*;
import java.net.*;
public class ClientToSendCalculable implements Serializable
{
public ClientToSendCalculable(int port)
{
try
(
Socket s = new Socket("localhost", port);
ObjectOutputStream writer = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream reader = new ObjectInputStream(s.getInputStream());
)
{
System.out.println("Connection was established!");
ClientToSendCalculable.Addition addition = new ClientToSendCalculable.Addition();
addition.firstAddendum = 5;
addition.secondAddendum = 7;
writer.writeObject(addition);
double res = (Double)reader.readObject();
System.out.println(res);
}
catch(Exception e)
{
e.printStackTrace();
}
}
private class Addition implements Calculable, Serializable
{
private double firstAddendum, secondAddendum;
public double calc()
{
return firstAddendum + secondAddendum;
}
}
public static void main(String[] args)
{
new ClientToSendCalculable(7777);
}
}
和 ServerToGetCalculable.java
import java.io.*;
import java.net.*;
public class ServerToGetCalculable
{
public ServerToGetCalculable(int port)
{
try
(
ServerSocket ss = new ServerSocket(port);
Socket s = ss.accept();
ObjectOutputStream writer = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream reader = new ObjectInputStream(s.getInputStream());
)
{
System.out.println("Got a client!");
Calculable calcObj = (Calculable)reader.readObject();
double res = calcObj.calc();
writer.writeObject(res);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{new ServerToGetCalculable(7777);}
}
我的问题是为什么 ClientToSendCalculable.java 应该实现 Serialized?我仅通过 Socket 发送其内部类 Addition.java,但我不单独发送 ClientToSendCalculable.java。这就是为什么在我看来,只要 Addition.java 是可序列化的就足够了,但如果我使 ClientToSendCalculable.java 不可序列化,我会在尝试执行这行代码时遇到异常:
writer.writeObject(addition);
最佳答案
Addition.java 是一个内部类(非静态) -> 它包含一个包含对封闭 ClientToSendCalculable 实例的引用的字段 -> 外部类的该字段必须被序列化 -> 它必须实现 Serialized 接口(interface)。
关于java - Java 中与 Socket 一起使用时可序列化的外部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44057755/