| 1 package org.sapia.ubik.net.nio.tcp.acceptor; 2 3 import java.nio.ByteBuffer ; 4 5 import org.sapia.ubik.net.nio.ChannelHandler; 6 import org.sapia.ubik.net.nio.Cycle; 7 8 17 public class EchoHandler implements ChannelHandler{ 18 19 String _in; 20 21 24 public boolean read(Cycle cycle) { 25 System.out.println("*** READ..."); 26 ByteBuffer buf = cycle.getByteBuffer(); 27 byte[] data = new byte[buf.remaining()]; 28 System.out.println("length: " + data.length); 29 buf.get(data); 30 try{ 31 _in = new String (data, "UTF-8"); 32 }catch(Exception e){ 33 34 e.printStackTrace(); 35 } 36 System.out.println("*** RECEIVED: " + _in); 37 cycle.state(Cycle.STATE_PROCESS); 38 return data.length > 0; 39 } 40 41 44 public boolean write(Cycle cycle) { 45 System.out.println("*** WRITE: " + _in); 46 if(_in == null){ 47 _in = new String ("No data received"); 48 } 49 _in = "ECHO: " + _in; 50 try{ 51 cycle.getByteBuffer().put(_in.getBytes("UTF-8")); 52 }catch(Exception e){ 53 e.printStackTrace(); 54 } 55 _in = null; 56 cycle.state(Cycle.STATE_COMPLETE); 57 return true; 58 } 59 60 61 64 65 68 public void process(Cycle cycle) { 69 System.out.println("*** PROCESS"); 70 cycle.state(Cycle.STATE_WRITE); 71 } 72 73 76 public void completed(Cycle cycle) { 77 System.out.println("*** COMPLETED"); 78 } 79 80 83 public void error(Cycle cycle) { 84 System.out.println("*** ERROR"); 85 cycle.getError().printStackTrace(); 86 } 87 } 88 | Popular Tags |