我想通过套接字通道传输序列化对象。我想将“嗨朋友”字符串作为序列化对象,然后将此对象写入套接字通道,而在另一端我想读取相同的对象并检索数据。
所有这些我想用 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;
}