日期:2014-05-16 浏览次数:21032 次
// output log to console
org.apache.log4j.BasicConfigurator.configure();
acceptor = new SocketAcceptor();
// Create a service configuration
SocketAcceptorConfig cfg = new SocketAcceptorConfig();
cfg.setReuseAddress(true);
// add a protocol codec, the protocol is wrapper from 0x00 to 0xff, and between 0x00 and 0xff is a message.
cfg.getFilterChain().addLast(
"protocolFilter",
new ProtocolCodecFilter(
new WrapperTagProtocolCodecFactory()));
// add logger filter
cfg.getFilterChain().addLast("logger", new LoggingFilter());
acceptor
.bind(new InetSocketAddress(PORT), new IoHandlerAdapter(){
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
// do something...
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
session.write("response something").join();
}
}, cfg);
public class WrapperTagProtocolCodecFactory extends
DemuxingProtocolCodecFactory {
public WrapperTagProtocolCodecFactory(){
super.register(WrapperTagDecoder.class);
super.register(WrapperTagEncoder.class);
}
public WrapperTagProtocolCodecFactory(String charset){
super.register(new WrapperTagDecoder(charset));
super.register(new WrapperTagEncoder(charset));
}
}
public class WrapperTagDecoder extends MessageDecoderAdapter {
private String charset = "gb2312";
private Logger logger = Logger.getLogger(WrapperTagDecoder.class);
public WrapperTagDecoder(String charset){
this.charset = charset;
}
public WrapperTagDecoder(){
}
public MessageDecoderResult decodable(IoSession session, ByteBuffer in) {
return MessageDecoderResult.OK;
}
public MessageDecoderResult decode(IoSession session, ByteBuffer in,
ProtocolDecoderOutput out) throws Exception {
InputStream stream = in.asInputStream();
int head = stream.read();
if(head == -1){
throw new IOException("read -1 byte");
}
logger.info("Read head 0x00.");
int b = -1;
ByteArrayOutputStream os = new ByteAr