001    //package edu.unima.ky.parallel;
002    
003    import java.io.IOException;
004    import java.nio.channels.SocketChannel;
005    import java.nio.ByteBuffer;
006    
007    /**
008     * ObjectBufferChannel.
009     * This class creates a communication channel using a socket.
010     * @author Heinz Kredel.
011     */
012    
013    public class ObjectBufferChannel implements ObjectChannel {
014    
015      /**
016       * default capacity for ByteBuffer.
017       */
018      final static int DEFAULT_CAPACITY = 4*1024; // 4k
019    
020      /**
021       * heap ByteBuffer.
022       */
023      final ByteBuffer hbb;
024    
025      /**
026       * object ByteBuffer wraper.
027       */
028      final ObjectBuffer ob;
029    
030      /**
031       * socket channel.
032       */
033      final SocketChannel soc;
034    
035    
036      /**
037       * Constructs a socket channel on the given socket s.
038       * @param s socket channel.
039       * @param cap capacity of ByteBuffer.
040       */
041      public ObjectBufferChannel(SocketChannel s, int cap) 
042                                 throws IOException {
043        soc = s;
044        hbb = ByteBuffer.allocate(cap);
045        // hbb.clear(); // or hbb.rewind() ?
046        ob = new ObjectBuffer( hbb );
047      }
048    
049      /**
050       * Constructs a socket channel on the given socket s.
051       * @param s socket channel.
052       */
053      public ObjectBufferChannel(SocketChannel s) 
054                                 throws IOException {
055          this(s,DEFAULT_CAPACITY);
056      }
057    
058      /**
059       * Sends an object.
060       * @param v Object to send.
061       */
062      public void send(Object v) throws IOException {
063        synchronized (hbb) {
064          hbb.clear();
065          ob.put(v);
066          hbb.flip();
067          soc.write( hbb );
068        }
069      }
070    
071    
072      /**
073       * Receives an object.
074       * @return received Object.
075       */
076      public Object receive() throws IOException, ClassNotFoundException {
077        Object v = null;
078        synchronized (hbb) { // use different buffer
079          hbb.clear(); // if remaining() == 0
080          soc.read( hbb );
081          hbb.flip();
082          v = ob.get();
083        }
084        return v;
085      }
086    
087    
088      /**
089       * Closes the channel.
090       */
091      public void close() {
092        if (soc != null) {
093          try { soc.close(); } catch (IOException e) { }
094        }
095      }
096    
097    }