我已经创建了工作套接字,当我尝试发送文本或数字时,它没问题,但是当我尝试发送我的自定义类对象时,我得到了 NullPointerException... 这是一些代码:
public boolean SendLi(List<Entity> list)
{
try {
out.writeObject(list);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Send: Error on OutputStream.write(byte[])");
}
return true;
}
public List<Entity> RecvLi()
{
List<Entity> data;
data = new ArrayList<Entity>();
try{
data = (List<Entity>) in.readObject();
} catch (IOException e) {
System.err.println("Send: Error on OutputStream.read(byte[]) - IOException");
return null;
} catch (ClassNotFoundException e) {
System.err.println("Send: Error on OutputStream.read(byte[]) - ClassNotFound");
e.printStackTrace();
}
return data;
}
实际上,我为列表编写了该代码,但我想要一些类似的函数来发送其他对象。 感谢您的回复!
最佳答案
在通过套接字发送自定义类之前,您需要序列化它。您要发送的对象
out.writeObject(list);
应该被序列化,你的类应该实现 java.io.Serialized 接口(interface)
关于Java 套接字 - 自定义对象发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8834881/