1 29 package transport.channel; 30 31 import java.io.ByteArrayInputStream ; 32 import java.io.IOException ; 33 import java.io.ObjectInputStream ; 34 import java.nio.ByteBuffer ; 35 import java.nio.channels.SocketChannel ; 36 37 import org.apache.commons.logging.Log; 38 import org.apache.commons.logging.LogFactory; 39 40 import transport.packet.Packet; 41 42 43 public final class ChannelUtils 44 { 45 private static final Log LOG = LogFactory.getLog(ChannelUtils.class); 46 47 public static final Packet readChannel(SocketChannel ch) throws IOException 48 { 49 if (LOG.isDebugEnabled()) 50 LOG.debug("Reading channel "+ch.hashCode()); 51 52 ch.configureBlocking(true); 53 Packet p = null; 54 ByteBuffer int_buf = ByteBuffer.allocate( 4 ); 55 int_buf.clear(); 56 while( int_buf.hasRemaining() ) 57 { 58 if( -1 == ch.read( int_buf ) ) 59 { 60 throw new IOException ( "end-of-stream" ); 61 } 62 } 63 64 int_buf.flip(); 65 int len = int_buf.getInt(); 66 67 byte[] data = new byte[ len ]; 69 ByteBuffer data_buf = ByteBuffer.wrap( data ); 70 data_buf.clear(); 71 while( data_buf.hasRemaining() ) 72 { 73 if( -1 == ch.read( data_buf ) ) 74 { 75 throw new IOException ( "end-of-stream" ); 76 } 77 } 78 79 ByteArrayInputStream bais = new ByteArrayInputStream ( data ); 81 ObjectInputStream ois = new ObjectInputStream ( bais ); 82 try 83 { 84 p = (Packet) ois.readObject(); 85 p.setChannelID(ch.hashCode()); 86 } 87 catch (ClassNotFoundException e) 88 { 89 IOException ioe = new IOException ("Packet deserialization failed"); 90 ioe.initCause(e); 91 throw ioe; 92 } 93 finally 94 { 95 ois.close(); 96 bais.close(); 97 data_buf = null; 98 int_buf = null; 99 } 100 101 return p; 102 } 103 104 } 105 | Popular Tags |