KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > ubik > net > nio > tcp > acceptor > EchoHandler


1 package org.sapia.ubik.net.nio.tcp.acceptor;
2
3 import java.nio.ByteBuffer JavaDoc;
4
5 import org.sapia.ubik.net.nio.ChannelHandler;
6 import org.sapia.ubik.net.nio.Cycle;
7
8 /**
9  * @author Yanick Duchesne
10  *
11  * <dl>
12  * <dt><b>Copyright:</b><dd>Copyright &#169; 2002-2005 <a HREF="http://www.sapia-oss.org">Sapia Open Source Software</a>. All Rights Reserved.</dd></dt>
13  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
14  * <a HREF="http://www.sapia-oss.org/license.html">license page</a> at the Sapia OSS web site</dd></dt>
15  * </dl>
16  */

17 public class EchoHandler implements ChannelHandler{
18   
19   String JavaDoc _in;
20   
21   /**
22    * @see org.sapia.ubik.net.nio.ChannelHandler#read(org.sapia.ubik.net.nio.Cycle)
23    */

24   public boolean read(Cycle cycle) {
25     System.out.println("*** READ...");
26     ByteBuffer JavaDoc 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 JavaDoc(data, "UTF-8");
32     }catch(Exception JavaDoc 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   /**
42    * @see org.sapia.ubik.net.nio.ChannelHandler#write(org.sapia.ubik.net.nio.Cycle)
43    */

44   public boolean write(Cycle cycle) {
45     System.out.println("*** WRITE: " + _in);
46     if(_in == null){
47       _in = new String JavaDoc("No data received");
48     }
49     _in = "ECHO: " + _in;
50     try{
51       cycle.getByteBuffer().put(_in.getBytes("UTF-8"));
52     }catch(Exception JavaDoc e){
53       e.printStackTrace();
54     }
55     _in = null;
56     cycle.state(Cycle.STATE_COMPLETE);
57     return true;
58   }
59   
60   
61   /**
62    * @see org.sapia.ubik.net.nio.ChannelHandler#handleCompleted(org.sapia.ubik.net.nio.State)
63    */

64   
65   /**
66    * @see org.sapia.ubik.net.nio.ChannelHandler#process(org.sapia.ubik.net.nio.Cycle)
67    */

68   public void process(Cycle cycle) {
69     System.out.println("*** PROCESS");
70     cycle.state(Cycle.STATE_WRITE);
71   }
72
73   /**
74    * @see org.sapia.ubik.net.nio.ChannelHandler#completed(org.sapia.ubik.net.nio.Cycle)
75    */

76   public void completed(Cycle cycle) {
77     System.out.println("*** COMPLETED");
78   }
79   
80   /**
81    * @see org.sapia.ubik.net.nio.ChannelHandler#error(Cycle)
82    */

83   public void error(Cycle cycle) {
84     System.out.println("*** ERROR");
85     cycle.getError().printStackTrace();
86   }
87 }
88
Popular Tags