http://www.blogjava.net/hankchen/archive/2012/02/04/369378.html
Nettyæ¯ä¸ä¸ªé«æ§è½çNIOéä¿¡æ¡æ¶ï¼æä¾å¼æ¥çãäºä»¶é©±å¨çç½ç»ç¼ç¨æ¨¡åã使ç¨Nettyå¯ä»¥æ¹ä¾¿ç¨æ·å¼ååç§å¸¸ç¨åè®®çç½ç»ç¨åºãä¾å¦ï¼TCPãUDPãHTTPççã
Nettyçææ°çæ¬æ¯3.2.7ï¼å®ç½å°åæ¯ï¼http://www.jboss.org/netty
æ¬æç主è¦ç®çæ¯åºäºNettyå®ç°ä¸ä¸ªéç¨äºè¿å¶åè®®çé«ææ°æ®ä¼ è¾ãåè®®æ¯éç¨çäºè¿å¶åè®®ï¼é«æå¹¶ä¸æ©å±æ§å¾å¥½ã
ä¸ä¸ªå¥½çåè®®æä¸¤ä¸ªæ åï¼
ï¼1ï¼çæçä¼ è¾æ°æ®è¦å°ï¼å³æ°æ®å缩æ¯è¦é«ãè¿æ ·å¯ä»¥åå°ç½ç»å¼éã
ï¼2ï¼ä¼ è¾æ°æ®åä¸å¡å¯¹è±¡ä¹é´ç转æ¢é度è¦å¿«ã
ï¼åæ æç¤ºï¼æ¬åæç« 欢è¿è½¬è½½ï¼ä½è¯·æ³¨æåºå¤ï¼hankchenï¼http://www.blogjava.net/hankchenï¼
ä¸ãåè®®çå®ä¹
æ 论æ¯è¯·æ±è¿æ¯ååºï¼æ¥æé½ç±ä¸ä¸ªéç¨æ¥æå¤´åå®é æ°æ®ç»æãæ¥æå¤´å¨åï¼æ°æ®å¨åã
ï¼1ï¼æ¥æå¤´ï¼ç±æ°æ®è§£æç±»åï¼æ°æ®è§£ææ¹æ³ï¼ç¼ç ï¼æ©å±åèï¼å é¿åº¦ç»æï¼å ±16个åèï¼
      ç¼ç æ¹å¼ï¼1byteï¼ãå å¯ï¼1byteï¼ãæ©å±1ï¼1byteï¼ãæ©å±2ï¼1byteï¼ãä¼è¯IDï¼4byteï¼ãå½ä»¤æè ç»æç ï¼4byteï¼ãæ°æ®å é¿ï¼4byteï¼
ï¼2ï¼æ°æ®ï¼ç±æ°æ®å é¿æå®ãè¯·æ±æå夿°æ®ãç±»å对åºä¸ºJAVAçMap<String,String>
Â Â Â Â Â Â æ°æ®æ ¼å¼å®ä¹ï¼
Â Â Â Â Â Â åæ®µ1é®åé¿åº¦Â Â Â åæ®µ1é®å åæ®µ1å¼é¿åº¦Â Â Â åæ®µ1å¼
Â Â Â Â Â Â åæ®µ2é®åé¿åº¦Â Â Â åæ®µ2é®å åæ®µ2å¼é¿åº¦Â Â Â åæ®µ2å¼
Â Â Â Â Â Â åæ®µ3é®åé¿åº¦Â Â Â åæ®µ3é®å åæ®µ3å¼é¿åº¦Â Â Â åæ®µ3å¼
      â¦Â   â¦Â   â¦Â   â¦
      é¿åº¦ä¸ºæ´åï¼å 4个åè
 代ç ä¸ç¨ä¸¤ä¸ªVo对象æ¥è¡¨ç¤ºï¼XLRequeståXLResponseã
 1

package  org.jboss.netty.example.xlsvr.vo;
 2

 3

import  java.util.HashMap;
 4

import  java.util.Map;
 5

 6
12

13

14
17

18
32
public  class  XLResponse {
33
    private byte encode;//Â æ°æ®ç¼ç æ ¼å¼ãå·²å®ä¹ï¼0ï¼UTF-8ï¼1ï¼GBKï¼2ï¼GB2312ï¼3ï¼ISO8859-1
34
    private byte encrypt;// å å¯ç±»åã0表示ä¸å å¯
35
    private byte extend1;// ç¨äºæ©å±åè®®ãææªå®ä¹ä»»ä½å¼
36
    private byte extend2;// ç¨äºæ©å±åè®®ãææªå®ä¹ä»»ä½å¼
37
    private int sessionid;// ä¼è¯ID
38
    private int result;//Â ç»æç
39
    private int length;//Â æ°æ®å é¿
40
   Â
41
    private Map<String,String> values=new HashMap<String, String>();
42
   Â
43
    private String ip;
44
   Â
45
    public void setValue(String key,String value){
46
       values.put(key, value);
47
   }
48
   Â
49
    public String getValue(String key){
50
        if (key==null) {
51
            return null;
52
       }
53
        return values.get(key);
54
   }
55
56
    public byte getEncode() {
57
        return encode;
58
   }
59
60
    public void setEncode(byte encode) {
61
        this.encode = encode;
62
   }
63
64
    public byte getEncrypt() {
65
        return encrypt;
66
   }
67
68
    public void setEncrypt(byte encrypt) {
69
        this.encrypt = encrypt;
70
   }
71
72
    public byte getExtend1() {
73
        return extend1;
74
   }
75
76
    public void setExtend1(byte extend1) {
77
        this.extend1 = extend1;
78
   }
79
80
    public byte getExtend2() {
81
        return extend2;
82
   }
83
84
    public void setExtend2(byte extend2) {
85
        this.extend2 = extend2;
86
   }
87
88
    public int getSessionid() {
89
        return sessionid;
90
   }
91
92
    public void setSessionid(int sessionid) {
93
        this.sessionid = sessionid;
94
   }
95
96
    public int getResult() {
97
        return result;
98
   }
99
100
    public void setResult(int result) {
101
        this.result = result;
102
   }
103
104
    public int getLength() {
105
        return length;
106
   }
107
108
    public void setLength(int length) {
109
        this.length = length;
110
   }
111
112
    public Map<String, String> getValues() {
113
        return values;
114
   }
115
116
    public String getIp() {
117
        return ip;
118
   }
119
120
    public void setIp(String ip) {
121
        this.ip = ip;
122
   }
123
124
    public void setValues(Map<String, String> values) {
125
        this.values = values;
126
   }
127
128
   @Override
129
    public String toString() {
130
        return "XLResponse [encode=" + encode + ", encrypt=" + encrypt + ", extend1=" + extend1 + ", extend2=" + extend2
131
                + ", sessionid=" + sessionid + ", result=" + result + ", length=" + length + ", values=" + values + ", ip=" + ip + "]";
132
   }
133
}
Â
 1

package  org.jboss.netty.example.xlsvr.vo;
 2

 3

import  java.util.HashMap;
 4

import  java.util.Map;
 5

 6
10

11
14

15
29
public  class  XLRequest {
30
    private byte encode;//Â æ°æ®ç¼ç æ ¼å¼ãå·²å®ä¹ï¼0ï¼UTF-8ï¼1ï¼GBKï¼2ï¼GB2312ï¼3ï¼ISO8859-1
31
    private byte encrypt;// å å¯ç±»åã0表示ä¸å å¯
32
    private byte extend1;// ç¨äºæ©å±åè®®ãææªå®ä¹ä»»ä½å¼
33
    private byte extend2;// ç¨äºæ©å±åè®®ãææªå®ä¹ä»»ä½å¼
34
    private int sessionid;// ä¼è¯ID
35
    private int command;// å½ä»¤
36
    private int length;//Â æ°æ®å é¿
37
   Â
38
    private Map<String,String> params=new HashMap<String, String>(); //åæ°
39
   Â
40
    private String ip;
41
42
    public byte getEncode() {
43
        return encode;
44
   }
45
46
    public void setEncode(byte encode) {
47
        this.encode = encode;
48
   }
49
50
    public byte getEncrypt() {
51
        return encrypt;
52
   }
53
54
    public void setEncrypt(byte encrypt) {
55
        this.encrypt = encrypt;
56
   }
57
58
    public byte getExtend1() {
59
        return extend1;
60
   }
61
62
    public void setExtend1(byte extend1) {
63
        this.extend1 = extend1;
64
   }
65
66
    public byte getExtend2() {
67
        return extend2;
68
   }
69
70
    public void setExtend2(byte extend2) {
71
        this.extend2 = extend2;
72
   }
73
74
    public int getSessionid() {
75
        return sessionid;
76
   }
77
78
    public void setSessionid(int sessionid) {
79
        this.sessionid = sessionid;
80
   }
81
82
    public int getCommand() {
83
        return command;
84
   }
85
86
    public void setCommand(int command) {
87
        this.command = command;
88
   }
89
90
    public int getLength() {
91
        return length;
92
   }
93
94
    public void setLength(int length) {
95
        this.length = length;
96
   }
97
98
    public Map<String, String> getParams() {
99
        return params;
100
   }
101
   Â
102
    public void setValue(String key,String value){
103
       params.put(key, value);
104
   }
105
   Â
106
    public String getValue(String key){
107
        if (key==null) {
108
            return null;
109
       }
110
        return params.get(key);
111
   }
112
113
    public String getIp() {
114
        return ip;
115
   }
116
117
    public void setIp(String ip) {
118
        this.ip = ip;
119
   }
120
121
    public void setParams(Map<String, String> params) {
122
        this.params = params;
123
   }
124
125
   @Override
126
    public String toString() {
127
        return "XLRequest [encode=" + encode + ", encrypt=" + encrypt + ", extend1=" + extend1 + ", extend2=" + extend2
128
                + ", sessionid=" + sessionid + ", command=" + command + ", length=" + length + ", params=" + params + ", ip=" + ip + "]";
129
   }
130
}
131

äºãåè®®çç¼ç åè§£ç
对äºèªå®ä¹äºè¿å¶åè®®ï¼ç¼ç è§£ç å¨å¾å¾æ¯Nettyå¼åçéç¹ãè¿éç´æ¥ç»åºç¸å ³ç±»ç代ç ã
Â
1

package  org.jboss.netty.example.xlsvr.codec;
2

3

import  java.nio.ByteBuffer;
4

5

import  org.jboss.netty.buffer.ChannelBuffer;
6

import  org.jboss.netty.buffer.ChannelBuffers;
7

import  org.jboss.netty.channel.ChannelHandlerContext;
8

import  org.jboss.netty.channel.Channels;
9

import  org.jboss.netty.channel.MessageEvent;
10

import  org.jboss.netty.channel.SimpleChannelDownstreamHandler;
11

import  org.jboss.netty.example.xlsvr.util.ProtocolUtil;
12

import  org.jboss.netty.example.xlsvr.vo.XLResponse;
13

import  org.slf4j.Logger;
14

import  org.slf4j.LoggerFactory;
15

16
20

21
24
public  class  XLServerEncoder extends  SimpleChannelDownstreamHandler {
25
   Logger logger=LoggerFactory.getLogger(XLServerEncoder.class);
26
   Â
27
   @Override
28
    public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
29
       XLResponse response=(XLResponse)e.getMessage();
30
       ByteBuffer headBuffer=ByteBuffer.allocate(16);
31
       Â
34
       headBuffer.put(response.getEncode());
35
       headBuffer.put(response.getEncrypt());
36
       headBuffer.put(response.getExtend1());
37
       headBuffer.put(response.getExtend2());
38
       headBuffer.putInt(response.getSessionid());
39
       headBuffer.putInt(response.getResult());
40
       Â
41
       Â
44
       ChannelBuffer dataBuffer=ProtocolUtil.encode(response.getEncode(),response.getValues());Â
45
        int length=dataBuffer.readableBytes();
46
       headBuffer.putInt(length);
47
       Â
51
       headBuffer.flip();
52
       ChannelBuffer totalBuffer=ChannelBuffers.dynamicBuffer();
53
       totalBuffer.writeBytes(headBuffer);
54
       logger.info("totalBuffer size="+totalBuffer.readableBytes());
55
       totalBuffer.writeBytes(dataBuffer);
56
       logger.info("totalBuffer size="+totalBuffer.readableBytes());
57
       Channels.write(ctx, e.getFuture(), totalBuffer);
58
   }
59
60
}
61

Â
1

package  org.jboss.netty.example.xlsvr.codec;
2

3

import  org.jboss.netty.buffer.ChannelBuffer;
4

import  org.jboss.netty.buffer.ChannelBuffers;
5

import  org.jboss.netty.channel.Channel;
6

import  org.jboss.netty.channel.ChannelHandlerContext;
7

import  org.jboss.netty.example.xlsvr.util.ProtocolUtil;
8

import  org.jboss.netty.example.xlsvr.vo.XLResponse;
9

import  org.jboss.netty.handler.codec.frame.FrameDecoder;
10

11
15

16
19
public  class  XLClientDecoder extends  FrameDecoder {
20
21
   @Override
22
    protected Object decode(ChannelHandlerContext context, Channel channel, ChannelBuffer buffer) throws Exception {
23
        if (buffer.readableBytes()<16) {
24
            return null;
25
       }
26
       buffer.markReaderIndex();
27
        byte encode=buffer.readByte();
28
        byte encrypt=buffer.readByte();
29
        byte extend1=buffer.readByte();
30
        byte extend2=buffer.readByte();
31
        int sessionid=buffer.readInt();
32
        int result=buffer.readInt();
33
        int length=buffer.readInt(); //Â æ°æ®å é¿
34
        if (buffer.readableBytes()<length) {
35
           buffer.resetReaderIndex();
36
            return null;
37
       }
38
       ChannelBuffer dataBuffer=ChannelBuffers.buffer(length);
39
       buffer.readBytes(dataBuffer, length);
40
       Â
41
       XLResponse response=new XLResponse();
42
       response.setEncode(encode);
43
       response.setEncrypt(encrypt);
44
       response.setExtend1(extend1);
45
       response.setExtend2(extend2);
46
       response.setSessionid(sessionid);
47
       response.setResult(result);
48
       response.setLength(length);
49
       response.setValues(ProtocolUtil.decode(encode, dataBuffer));
50
       response.setIp(ProtocolUtil.getClientIp(channel));
51
        return response;
52
   }
53
54
}
Â
 1

package  org.jboss.netty.example.xlsvr.util;
 2

 3

import  java.net.SocketAddress;
 4

import  java.nio.charset.Charset;
 5

import  java.util.HashMap;
 6

import  java.util.Map;
 7

import  java.util.Map.Entry;
 8

 9

import  org.jboss.netty.buffer.ChannelBuffer;
10

import  org.jboss.netty.buffer.ChannelBuffers;
11

import  org.jboss.netty.channel.Channel;
12

13
17
public  class  ProtocolUtil {
18
   Â
19
   Â
25
    public static ChannelBuffer encode(int encode,Map<String,String> values){
26
       ChannelBuffer totalBuffer=null;
27
        if (values!=null && values.size()>0) {
28
           totalBuffer=ChannelBuffers.dynamicBuffer();
29
            int length=0,index=0;
30
           ChannelBuffer [] channelBuffers=new ChannelBuffer[values.size()];
31
           Charset charset=XLCharSetFactory.getCharset(encode);
32
            for(Entry<String,String> entry:values.entrySet()){
33
               String key=entry.getKey();
34
               String value=entry.getValue();
35
               ChannelBuffer buffer=ChannelBuffers.dynamicBuffer();
36
               buffer.writeInt(key.length());
37
               buffer.writeBytes(key.getBytes(charset));
38
               buffer.writeInt(value.length());
39
               buffer.writeBytes(value.getBytes(charset));
40
               channelBuffers[index++]=buffer;
41
               length+=buffer.readableBytes();
42
           }
43
           Â
44
            for (int i = 0; i < channelBuffers.length; i++) {
45
               totalBuffer.writeBytes(channelBuffers[i]);
46
           }
47
       }
48
        return totalBuffer;
49
   }
50
   Â
51
   Â
57
    public static Map<String,String> decode(int encode,ChannelBuffer dataBuffer){
58
       Map<String,String> dataMap=new HashMap<String, String>();
59
        if (dataBuffer!=null && dataBuffer.readableBytes()>0) {
60
            int processIndex=0,length=dataBuffer.readableBytes();
61
           Charset charset=XLCharSetFactory.getCharset(encode);
62
            while(processIndex<length){
63
               Â
66
                int size=dataBuffer.readInt();
67
                byte [] contents=new byte [size];
68
               dataBuffer.readBytes(contents);
69
               String key=new String(contents, charset);
70
               processIndex=processIndex+size+4;
71
               Â
74
               size=dataBuffer.readInt();
75
               contents=new byte [size];
76
               dataBuffer.readBytes(contents);
77
               String value=new String(contents, charset);
78
               dataMap.put(key, value);
79
               processIndex=processIndex+size+4;
80
           }
81
       }
82
        return dataMap;
83
   }
84
   Â
85
   Â
90
    public static String getClientIp(Channel channel){
91
       Â
94
       SocketAddress address = channel.getRemoteAddress();
95
       String ip = "";
96
        if (address != null) {
97
           ip = address.toString().trim();
98
            int index = ip.lastIndexOf(':');
99
            if (index < 1) {
100
               index = ip.length();
101
           }
102
           ip = ip.substring(1, index);
103
       }
104
        if (ip.length() > 15) {
105
           ip = ip.substring(Math.max(ip.indexOf("/") + 1, ip.length() - 15));
106
       }
107
        return ip;
108
   }
109
}
110

ä¸ãæå¡å¨ç«¯å®ç°
æå¡å¨ç«¯æä¾çåè½æ¯ï¼
1ãæ¥æ¶å®¢æ·ç«¯ç请æ±ï¼éå ³éå½ä»¤ï¼ï¼è¿åXLResponseç±»åçæ°æ®ã
2ã妿客æ·ç«¯çè¯·æ±æ¯å ³éå½ä»¤ï¼shutdownï¼åæå¡å¨ç«¯å ³éèªèº«è¿ç¨ã
为äºå±ç¤ºå¤åè®®çè¿ç¨ï¼è¿é客æ·ç«¯ç请æ±éç¨çæ¯åºäºé®æ¬è¡ï¼\n\rï¼çåè®®ã
å ·ä½ä»£ç å¦ä¸ï¼
1

package  org.jboss.netty.example.xlsvr;
2

3

import  java.net.InetSocketAddress;
4

import  java.util.concurrent.Executors;
5

6

import  org.jboss.netty.bootstrap.ServerBootstrap;
7

import  org.jboss.netty.channel.Channel;
8

import  org.jboss.netty.channel.ChannelPipeline;
9

import  org.jboss.netty.channel.group.ChannelGroup;
10

import  org.jboss.netty.channel.group.ChannelGroupFuture;
11

import  org.jboss.netty.channel.group.DefaultChannelGroup;
12

import  org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
13

import  org.jboss.netty.example.xlsvr.codec.XLServerEncoder;
14

import  org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
15

import  org.jboss.netty.handler.codec.frame.Delimiters;
16

import  org.jboss.netty.handler.codec.string.StringDecoder;
17

import  org.jboss.netty.util.CharsetUtil;
18

import  org.slf4j.Logger;
19

import  org.slf4j.LoggerFactory;
20

21
25

26
public  class  XLServer {
27
    public static final int port =8080;
28
    public static final Logger logger=LoggerFactory.getLogger(XLServer.class);
29
    public static final ChannelGroup allChannels=new DefaultChannelGroup("XLServer");
30
    private static final ServerBootstrap serverBootstrap=new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
31
   Â
32
    public static void main(String [] args){
33
        try {
34
           XLServer.startup();
35
       } catch (Exception e) {
36
           e.printStackTrace();
37
       }
38
   }
39
   Â
40
    public static boolean startup() throws Exception{
41
       Â
46
       ChannelPipeline pipeline=serverBootstrap.getPipeline();Â
47
       Â
50
       pipeline.addLast("frameDecoder", new DelimiterBasedFrameDecoder(80, Delimiters.lineDelimiter()));
51
       pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
52
       pipeline.addLast("encoder", new XLServerEncoder());
53
       pipeline.addLast("handler", new XLServerHandler());
54
       Â
55
       serverBootstrap.setOption("child.tcpNoDelay", true); //注æchildåç¼
56
       serverBootstrap.setOption("child.keepAlive", true); //注æchildåç¼
57
       Â
58
       Â
61
       Channel channel=serverBootstrap.bind(new InetSocketAddress(port));
62
       allChannels.add(channel);
63
       logger.info("server is started on port "+port);
64
        return false;
65
   }
66
   Â
67
    public static void shutdown() throws Exception{
68
        try {
69
           Â
72
           ChannelGroupFuture future=allChannels.close();
73
           future.awaitUninterruptibly();//é»å¡ï¼ç´å°æå¡å¨å ³é
74
            //serverBootstrap.releaseExternalResources();
75
       } catch (Exception e) {
76
           e.printStackTrace();
77
           logger.error(e.getMessage(),e);
78
       }
79
        finally{
80
           logger.info("server is shutdown on port "+port);
81
           System.exit(1);
82
       }
83
   }
84
}
85

Â
 1

package  org.jboss.netty.example.xlsvr;
 2

 3

import  java.util.Random;
 4

 5

import  org.jboss.netty.channel.Channel;
 6

import  org.jboss.netty.channel.ChannelFuture;
 7

import  org.jboss.netty.channel.ChannelHandlerContext;
 8

import  org.jboss.netty.channel.ChannelHandler.Sharable;
 9

import  org.jboss.netty.channel.ChannelStateEvent;
10

import  org.jboss.netty.channel.ExceptionEvent;
11

import  org.jboss.netty.channel.MessageEvent;
12

import  org.jboss.netty.channel.SimpleChannelHandler;
13

import  org.jboss.netty.example.xlsvr.vo.XLResponse;
14

import  org.slf4j.Logger;
15

import  org.slf4j.LoggerFactory;
16

17
21

22

@Sharable
23
public  class  XLServerHandler extends  SimpleChannelHandler {
24
    private static final Logger logger=LoggerFactory.getLogger(XLServerHandler.class);
25
   Â
26
   @Override
27
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
28
       logger.info("messageReceived");
29
        if (e.getMessage() instanceof String) {
30
           String content=(String)e.getMessage();
31
           logger.info("content is "+content);
32
            if ("shutdown".equalsIgnoreCase(content)) {
33
                //e.getChannel().close();
34
               XLServer.shutdown();
35
           }else {
36
               sendResponse(ctx);
37
           }
38
       }else {
39
           logger.error("message is not a String.");
40
           e.getChannel().close();
41
       }
42
   }
43
44
   @Override
45
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
46
       logger.error(e.getCause().getMessage(),e.getCause());
47
       e.getCause().printStackTrace();
48
       e.getChannel().close();
49
   }
50
51
   @Override
52
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
53
       logger.info("channelConnected");
54
       sendResponse(ctx);
55
   }
56
57
   @Override
58
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
59
       logger.info("channelClosed");
60
        //å é¤éé
61
       XLServer.allChannels.remove(e.getChannel());
62
   }
63
64
   @Override
65
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
66
       logger.info("channelDisconnected");
67
        super.channelDisconnected(ctx, e);
68
   }
69
70
   @Override
71
    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
72
       logger.info("channelOpen");
73
        //å¢å éé
74
       XLServer.allChannels.add(e.getChannel());
75
   }
76
77
   Â
83
    private ChannelFuture sendResponse(ChannelHandlerContext ctx){
84
       Channel channel=ctx.getChannel();
85
       Random random=new Random();
86
       XLResponse response=new XLResponse();
87
       response.setEncode((byte)0);
88
       response.setResult(1);
89
       response.setValue("name","hankchen");
90
       response.setValue("time", String.valueOf(System.currentTimeMillis()));
91
       response.setValue("age",String.valueOf(random.nextInt()));
92
       Â
96
       ChannelFuture future=channel.write(response); //åéå 容
97
        return future;
98
   }
99
}
100

åã客æ·ç«¯å®ç°
客æ·ç«¯çåè½æ¯è¿æ¥æå¡å¨ï¼åé10次请æ±ï¼ç¶ååéå ³éæå¡å¨çå½ä»¤ï¼æå主å¨å ³é客æ·ç«¯ã
å ³é®ä»£ç å¦ä¸ï¼
1
6

7
12
public  class  XLClient {
13
    public static final int port =XLServer.port;
14
    public static final String host ="localhost";
15
    private static final Logger logger=LoggerFactory.getLogger(XLClient.class);
16
    private static final NioClientSocketChannelFactory clientSocketChannelFactory=new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool());
17
    private static final ClientBootstrap clientBootstrap=new ClientBootstrap(clientSocketChannelFactory);
18
   Â
19
   Â
23
    public static void main(String[] args) throws Exception {
24
       ChannelFuture future=XLClient.startup();
25
       logger.info("future state is "+future.isSuccess());
26
   }
27
   Â
28
   Â
33
    public static ChannelFuture startup() throws Exception {
34
       Â
40
       clientBootstrap.setPipelineFactory(new XLClientPipelineFactory()); //åªè½è¿æ ·è®¾ç½®
41
       Â
44
       clientBootstrap.setOption("tcpNoDelay", true);
45
       clientBootstrap.setOption("keepAlive", true);
46
       Â
47
       ChannelFuture future=clientBootstrap.connect(new InetSocketAddress(host, port));
48
       Â
51
       future.awaitUninterruptibly();
52
       Â
56
        if (!future.isSuccess()) {
57
           future.getCause().printStackTrace();
58
       }else {
59
           logger.info("client is connected to server "+host+":"+port);
60
       }
61
        return future;
62
   }
63
   Â
64
   Â
69
    public static void shutdown(ChannelFuture future) throws Exception{
70
        try {
71
           Â
74
           future.getChannel().close().awaitUninterruptibly();
75
            //future.getChannel().getCloseFuture().awaitUninterruptibly();
76
           Â
81
           clientBootstrap.releaseExternalResources();
82
       } catch (Exception e) {
83
           e.printStackTrace();
84
           logger.error(e.getMessage(),e);
85
       }
86
        finally{
87
           System.exit(1);
88
           logger.info("client is shutdown to server "+host+":"+port);
89
       }
90
   }
91
}
Â
1
public  class  XLClientPipelineFactory implements  ChannelPipelineFactory {
2
3
   @Override
4
    public ChannelPipeline getPipeline() throws Exception {
5
       ChannelPipeline pipeline=Channels.pipeline();
6
       Â
10
       pipeline.addLast("decoder", new XLClientDecoder());
11
       Â
14
       pipeline.addLast("handler", new XLClientHandler());
15
        return pipeline;
16
   }
17
18
}
Â
1
6

7
12
public  class  XLClientHandler extends  SimpleChannelHandler {
13
    private static final Logger logger=LoggerFactory.getLogger(XLClientHandler.class);
14
    private final AtomicInteger count=new AtomicInteger(0); //计æ°å¨
15
   Â
16
   @Override
17
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
18
       processMethod1(ctx, e); //å¤çæ¹å¼ä¸
19
   }
20
   Â
21
   Â
26
    public void processMethod1(ChannelHandlerContext ctx, MessageEvent e) throws Exception{
27
       logger.info("processMethod1â¦â¦,count="+count.addAndGet(1));
28
       XLResponse serverTime=(XLResponse)e.getMessage();
29
       logger.info("messageReceived,content:"+serverTime.toString());
30
       Thread.sleep(1000);
31
       Â
32
        if (count.get()<10) {
33
            //仿°åé请æ±è·åææ°çæå¡å¨æ¶é´
34
           ctx.getChannel().write(ChannelBuffers.wrappedBuffer("again\r\n".getBytes()));
35
       }else{
36
            //仿°åé请æ±å ³éæå¡å¨
37
           ctx.getChannel().write(ChannelBuffers.wrappedBuffer("shutdown\r\n".getBytes()));
38
       }
39
   }
40
   Â
41
   @Override
42
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
43
       logger.info("exceptionCaught");
44
       e.getCause().printStackTrace();
45
       ctx.getChannel().close();
46
   }
47
48
   @Override
49
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
50
       logger.info("channelClosed");
51
        super.channelClosed(ctx, e);
52
   }
53
   Â
54
   Â
55
}
å ¨æä»£ç è¾å¤ï¼åäºå¾å¤æ³¨éï¼å¸æå¯¹è¯»è æç¨ï¼è°¢è°¢ï¼
ï¼åæ æç¤ºï¼æ¬åæç« 欢è¿è½¬è½½ï¼ä½è¯·æ³¨æåºå¤ï¼hankchenï¼http://www.blogjava.net/hankchenï¼