I want to transmit a serialized object over a socket channel. I want make "Hi friend" string as serialized object and then write this object in socket channel while in the other end i want to read the same object and retrieve the data.
All these things I want to do using Java SocketChannel
. How to do this?
I have tried like below, but did not get any data in the recipient side.
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;
}