code_junkie

Java: Are concurrent reads and writes possible on a blocking SocketChannel via Object(In|Out)putStreams?

Nov 11th, 2011
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. socketChannel = SocketChannel.open(destNode);
  2. objectOutputStream = new ObjectOutputStream(Channels.newOutputStream(socketChannel));
  3. objectInputStream = new ObjectInputStream(Channels.newInputStream(socketChannel));
  4.  
  5. Thread replyThread = new Thread("SendRunnable-ReplyThread") {
  6. @Override
  7. public void run() {
  8. try {
  9. byte reply = objectInputStream.readByte();//(A)
  10. //..process reply
  11. } catch (Throwable e) {
  12. logger.warn("Problem reading receive reply.", e);
  13. }
  14. }
  15. };
  16. replyThread.start();
  17.  
  18. objectOutputStream.writeObject(someObject);//(B)
  19. //..more writing
  20.  
  21. Socket socket = new Socket();
  22. socket.connect(destNode);
  23. final OutputStream outputStream = socket.getOutputStream();
  24. objectOutputStream = new ObjectOutputStream(outputStream);
  25. objectInputStream = new ObjectInputStream(socket.getInputStream());
  26.  
  27. public InputStream getInputStream() throws IOException {
  28. return Channels.newInputStream(new ReadableByteChannel() {
  29. public int read(ByteBuffer dst) throws IOException {
  30. return socketChannel.read(dst);
  31. }
  32. public void close() throws IOException {
  33. socketChannel.close();
  34. }
  35. public boolean isOpen() {
  36. return socketChannel.isOpen();
  37. }
  38. });
  39. }
  40.  
  41. public OutputStream getOutputStream() throws IOException {
  42. return Channels.newOutputStream(socketChannel);
  43. }
Add Comment
Please, Sign In to add comment