如何在套接字通道中发送和接收序列化对象
我想通过套接字通道传输序列化对象。我想将“Hi friend”字符串作为序列化对象,然后在套接字通道中写入此对象,而在另一端,我想读取相同的对象并检索数据。
我想用Java做的所有这些事情。如何做到这一点?我已经尝试了如下,但没有在收件人端获得任何数据。SocketChannel
private static void writeObject(Object obj, SelectionKey selectionKey) {
ObjectOutputStream oos;
try {
SocketChannel channel = (SocketChannel) selectionKey.channel();
oos = new ObjectOutputStream(Channels.newOutputStream(channel));
oos.writeObject(obj);
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static Object readObject(SelectionKey selectionKey) {
ObjectInputStream ois;
Object obj = new Object();
SocketChannel channel = (SocketChannel) selectionKey.channel();
try {
ois = new ObjectInputStream(Channels.newInputStream(channel));
obj = ois.readObject();
} catch (Exception ex) {
ex.printStackTrace();
}
return obj;
}