博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Apache Mina自定义编解码案例 .
阅读量:4038 次
发布时间:2019-05-24

本文共 15634 字,大约阅读时间需要 52 分钟。

Mina中已经自带的编解码类:

TextLineCodecFactory:基于文本的,根据回车换行来断点传输数据

ProtocolCodecFactory:自定义协议的编解码数据传输

ObjectSerializationCodecFactory:对象序列化传输

DemuxingProtocolCodecFactory:复用传输

自定义通信协议:

FlightSearch 1.0 \n

startcity:BJS \n
endcity:PEK \n
flightway:1 \n
date:2011-08-10 \n

Domain对象

[java]
  1. package domain;  
  2.   
  3. /** 
  4.  * @function :  
  5.  * @author   :jy 
  6.  * @company  :万里网 
  7.  * @date     :2011-8-7 
  8.  */  
  9. public class Flight {  
  10.     public String startCity;  
  11.     public String endCity;  
  12.     public String flightway;  
  13.     public String date;  
  14.     public String fromDate;  
  15.     public String subclass1;  
  16.     public String flight1;  
  17.       
  18.     /** 
  19.      * 返回出发城市 
  20.      * @return 
  21.      */  
  22.     public String getStartCity() {  
  23.         return startCity;  
  24.     }  
  25.     public void setStartCity(String startCity) {  
  26.         this.startCity = startCity;  
  27.     }  
  28.     /** 
  29.      * 返回到达城市 
  30.      * @return 
  31.      */  
  32.     public String getEndCity() {  
  33.         return endCity;  
  34.     }  
  35.     public void setEndCity(String endCity) {  
  36.         this.endCity = endCity;  
  37.     }  
  38.     /** 
  39.      * 返回行程类型 
  40.      * @return 
  41.      */  
  42.     public String getFlightway() {  
  43.         return flightway;  
  44.     }  
  45.     public void setFlightway(String flightway) {  
  46.         this.flightway = flightway;  
  47.     }  
  48.     /** 
  49.      * 返回出发日期 
  50.      * @return 
  51.      */  
  52.     public String getDate() {  
  53.         return date;  
  54.     }  
  55.     public void setDate(String date) {  
  56.         this.date = date;  
  57.     }  
  58.     @Override  
  59.     public String toString() {  
  60.         return "Flight [startCity=" + startCity + ", endCity=" + endCity + ", flightway=" + flightway + ", date="  
  61.                 + date + "]";  
  62.     }  
  63.     /** 
  64.      * 返回往返日期 
  65.      * @return 
  66.      */  
  67.     public String getFromDate() {  
  68.         return fromDate;  
  69.     }  
  70.     public void setFromDate(String fromDate) {  
  71.         this.fromDate = fromDate;  
  72.     }  
  73.     public String getFlight1() {  
  74.         return flight1;  
  75.     }  
  76.     public void setFlight1(String flight1) {  
  77.         this.flight1 = flight1;  
  78.     }  
  79.     public String getSubclass1() {  
  80.         return subclass1;  
  81.     }  
  82.     public void setSubclass1(String subclass1) {  
  83.         this.subclass1 = subclass1;  
  84.     }  
  85. }  
package domain;/** * @function :  * @author   :jy * @company  :万里网 * @date     :2011-8-7 */public class Flight {	public String startCity;	public String endCity;	public String flightway;	public String date;	public String fromDate;	public String subclass1;	public String flight1;		/**	 * 返回出发城市	 * @return	 */	public String getStartCity() {		return startCity;	}	public void setStartCity(String startCity) {		this.startCity = startCity;	}	/**	 * 返回到达城市	 * @return	 */	public String getEndCity() {		return endCity;	}	public void setEndCity(String endCity) {		this.endCity = endCity;	}	/**	 * 返回行程类型	 * @return	 */	public String getFlightway() {		return flightway;	}	public void setFlightway(String flightway) {		this.flightway = flightway;	}	/**	 * 返回出发日期	 * @return	 */	public String getDate() {		return date;	}	public void setDate(String date) {		this.date = date;	}	@Override	public String toString() {		return "Flight [startCity=" + startCity + ", endCity=" + endCity + ", flightway=" + flightway + ", date="				+ date + "]";	}	/**	 * 返回往返日期	 * @return	 */	public String getFromDate() {		return fromDate;	}	public void setFromDate(String fromDate) {		this.fromDate = fromDate;	}	public String getFlight1() {		return flight1;	}	public void setFlight1(String flight1) {		this.flight1 = flight1;	}	public String getSubclass1() {		return subclass1;	}	public void setSubclass1(String subclass1) {		this.subclass1 = subclass1;	}}
服务器端编码

[java]
  1. package server;  
  2.   
  3. import java.nio.charset.Charset;  
  4. import java.nio.charset.CharsetEncoder;  
  5.   
  6. import org.apache.mina.core.buffer.IoBuffer;  
  7. import org.apache.mina.core.session.IoSession;  
  8. import org.apache.mina.filter.codec.ProtocolEncoderAdapter;  
  9. import org.apache.mina.filter.codec.ProtocolEncoderOutput;  
  10.   
  11. /** 
  12.  * @function :  
  13.  * @author   :jy 
  14.  * @company  :万里网 
  15.  * @date     :2011-8-7 
  16.  */  
  17. public class FlightEncoder extends ProtocolEncoderAdapter {  
  18.     private final Charset charset = Charset.forName("UTF-8");  
  19.     /*  
  20.      * 服务器端编码无需处理,直接将接收到的数据向下传递 
  21.      */  
  22.     @Override  
  23.     public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {  
  24.         IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);  
  25.           
  26.         CharsetEncoder ce = charset.newEncoder();  
  27.           
  28.         buf.putString((String)message, ce);  
  29.           
  30.         buf.flip();  
  31.           
  32.         out.write(buf);  
  33.     }  
  34.   
  35. }  
package server;import java.nio.charset.Charset;import java.nio.charset.CharsetEncoder;import org.apache.mina.core.buffer.IoBuffer;import org.apache.mina.core.session.IoSession;import org.apache.mina.filter.codec.ProtocolEncoderAdapter;import org.apache.mina.filter.codec.ProtocolEncoderOutput;/** * @function :  * @author   :jy * @company  :万里网 * @date     :2011-8-7 */public class FlightEncoder extends ProtocolEncoderAdapter {	private final Charset charset = Charset.forName("UTF-8");	/* 	 * 服务器端编码无需处理,直接将接收到的数据向下传递	 */	@Override	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {		IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);				CharsetEncoder ce = charset.newEncoder();				buf.putString((String)message, ce);				buf.flip();				out.write(buf);	}}
重点是服务器端解码

[java]
  1. package server;  
  2.   
  3. import java.nio.charset.Charset;  
  4. import java.nio.charset.CharsetDecoder;  
  5.   
  6. import org.apache.mina.core.buffer.IoBuffer;  
  7. import org.apache.mina.core.session.IoSession;  
  8. import org.apache.mina.filter.codec.CumulativeProtocolDecoder;  
  9. import org.apache.mina.filter.codec.ProtocolDecoderAdapter;  
  10. import org.apache.mina.filter.codec.ProtocolDecoderOutput;  
  11.   
  12. import domain.Flight;  
  13.   
  14. /** 
  15.  * @function :  
  16.  * @author   :jy 
  17.  * @company  :万里网 
  18.  * @date     :2011-8-7 
  19.  */  
  20. public class FlightDecoder extends CumulativeProtocolDecoder {  
  21.   
  22.     @Override  
  23.     protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {  
  24.         IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);  
  25.         CharsetDecoder cd = Charset.forName("UTF-8").newDecoder();  
  26.           
  27.         int ColumnNumber = 0;  
  28.         String status="",startCity="",endCity="",flightway="",date="";  
  29.           
  30.         int TextLineNumber = 1;  
  31.           
  32.         Flight flight = new Flight();  
  33.   
  34.         /** 
  35.          * FlightSearch 1.0 \n 
  36.          * startcity:BJS \n 
  37.          * endcity:PEK \n 
  38.          * flightway:1 \n 
  39.          * date:2011-08-10 \n 
  40.          */  
  41.         while(in.hasRemaining()){  
  42.             byte b = in.get();  
  43.             buf.put(b);  
  44.             if(b == 10 && TextLineNumber <= 5){  
  45.                 ColumnNumber++;  
  46.                 if(TextLineNumber == 1){  
  47.                     buf.flip();  
  48.                     status = buf.getString(ColumnNumber, cd);  
  49.                 }  
  50.                   
  51.                 if(TextLineNumber == 2){  
  52.                     buf.flip();  
  53.                     startCity = buf.getString(ColumnNumber, cd).split(":")[1];  
  54.                     startCity = startCity.substring(0, startCity.length()-1);  
  55.                     flight.setStartCity(startCity);  
  56.                 }  
  57.                   
  58.                 if(TextLineNumber == 3){  
  59.                     buf.flip();  
  60.                     endCity = buf.getString(ColumnNumber, cd).split(":")[1];  
  61.                     endCity = endCity.substring(0, endCity.length()-1);  
  62.                     flight.setEndCity(endCity);  
  63.                 }  
  64.                   
  65.                 if(TextLineNumber == 4){  
  66.                     buf.flip();  
  67.                     flightway = buf.getString(ColumnNumber, cd).split(":")[1];  
  68.                     flightway = flightway.substring(0, flightway.length()-1);  
  69.                     flight.setFlightway(flightway);  
  70.                 }  
  71.                   
  72.                 if(TextLineNumber == 5){  
  73.                     buf.flip();  
  74.                     date = buf.getString(ColumnNumber, cd).split(":")[1];  
  75.                     date = date.substring(0, date.length()-1);  
  76.                     flight.setDate(date);  
  77.                     break;  
  78.                 }  
  79.                   
  80.                 ColumnNumber = 0;  
  81.                 buf.clear();  
  82.                 TextLineNumber++;  
  83.             }else{  
  84.                 ColumnNumber++;  
  85.             }  
  86.         }  
  87.         out.write(flight);  
  88.         return false;  
  89.     }  
  90.   
  91. }  
package server;import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import org.apache.mina.core.buffer.IoBuffer;import org.apache.mina.core.session.IoSession;import org.apache.mina.filter.codec.CumulativeProtocolDecoder;import org.apache.mina.filter.codec.ProtocolDecoderAdapter;import org.apache.mina.filter.codec.ProtocolDecoderOutput;import domain.Flight;/** * @function :  * @author   :jy * @company  :万里网 * @date     :2011-8-7 */public class FlightDecoder extends CumulativeProtocolDecoder {	@Override	protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {		IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);		CharsetDecoder cd = Charset.forName("UTF-8").newDecoder();				int ColumnNumber = 0;		String status="",startCity="",endCity="",flightway="",date="";				int TextLineNumber = 1;				Flight flight = new Flight();		/**		 * FlightSearch 1.0 \n		 * startcity:BJS \n		 * endcity:PEK \n		 * flightway:1 \n		 * date:2011-08-10 \n		 */		while(in.hasRemaining()){			byte b = in.get();			buf.put(b);			if(b == 10 && TextLineNumber <= 5){				ColumnNumber++;				if(TextLineNumber == 1){					buf.flip();					status = buf.getString(ColumnNumber, cd);				}								if(TextLineNumber == 2){					buf.flip();					startCity = buf.getString(ColumnNumber, cd).split(":")[1];					startCity = startCity.substring(0, startCity.length()-1);					flight.setStartCity(startCity);				}								if(TextLineNumber == 3){					buf.flip();					endCity = buf.getString(ColumnNumber, cd).split(":")[1];					endCity = endCity.substring(0, endCity.length()-1);					flight.setEndCity(endCity);				}								if(TextLineNumber == 4){					buf.flip();					flightway = buf.getString(ColumnNumber, cd).split(":")[1];					flightway = flightway.substring(0, flightway.length()-1);					flight.setFlightway(flightway);				}								if(TextLineNumber == 5){					buf.flip();					date = buf.getString(ColumnNumber, cd).split(":")[1];					date = date.substring(0, date.length()-1);					flight.setDate(date);					break;				}								ColumnNumber = 0;				buf.clear();				TextLineNumber++;			}else{				ColumnNumber++;			}		}		out.write(flight);		return false;	}}
服务器端编解码工厂

[java]
  1. package server;  
  2.   
  3. import org.apache.mina.core.session.IoSession;  
  4. import org.apache.mina.filter.codec.ProtocolCodecFactory;  
  5. import org.apache.mina.filter.codec.ProtocolDecoder;  
  6. import org.apache.mina.filter.codec.ProtocolEncoder;  
  7.   
  8. /** 
  9.  * @function :  
  10.  * @author   :jy 
  11.  * @company  :万里网 
  12.  * @date     :2011-8-7 
  13.  */  
  14. public class FlightCodecFactory implements ProtocolCodecFactory {  
  15.     private final ProtocolEncoder encoder = new FlightEncoder();  
  16.     private final ProtocolDecoder decoder = new FlightDecoder();  
  17.   
  18.     @Override  
  19.     public ProtocolDecoder getDecoder(IoSession session) throws Exception {  
  20.         return decoder;  
  21.     }  
  22.   
  23.     @Override  
  24.     public ProtocolEncoder getEncoder(IoSession session) throws Exception {  
  25.         return encoder;  
  26.     }  
  27.   
  28. }  
package server;import org.apache.mina.core.session.IoSession;import org.apache.mina.filter.codec.ProtocolCodecFactory;import org.apache.mina.filter.codec.ProtocolDecoder;import org.apache.mina.filter.codec.ProtocolEncoder;/** * @function :  * @author   :jy * @company  :万里网 * @date     :2011-8-7 */public class FlightCodecFactory implements ProtocolCodecFactory {	private final ProtocolEncoder encoder = new FlightEncoder();	private final ProtocolDecoder decoder = new FlightDecoder();	@Override	public ProtocolDecoder getDecoder(IoSession session) throws Exception {		return decoder;	}	@Override	public ProtocolEncoder getEncoder(IoSession session) throws Exception {		return encoder;	}}

下面是客户端的编解码

重点是编码,需要将数据组装成协议格式,发送给服务器

[java]
  1. package client;  
  2.   
  3. import java.nio.charset.Charset;  
  4. import java.nio.charset.CharsetEncoder;  
  5.   
  6. import org.apache.mina.core.buffer.IoBuffer;  
  7. import org.apache.mina.core.session.IoSession;  
  8. import org.apache.mina.filter.codec.ProtocolEncoderAdapter;  
  9. import org.apache.mina.filter.codec.ProtocolEncoderOutput;  
  10.   
  11. import domain.Flight;  
  12.   
  13.   
  14. /** 
  15.  * @function :  
  16.  * @author   :jy 
  17.  * @company  :万里网 
  18.  * @date     :2011-8-7 
  19.  */  
  20. public class FlightClientEncoder extends ProtocolEncoderAdapter {  
  21.     private final Charset charset;  
  22.       
  23.     public FlightClientEncoder(){  
  24.         this.charset = Charset.forName("UTF-8");  
  25.     }  
  26.   
  27.     @Override  
  28.     public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {  
  29.         Flight flight = (Flight)message;  
  30.           
  31.         IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);  
  32.           
  33.         CharsetEncoder ce = charset.newEncoder();  
  34.           
  35.         buf.putString("Flight Search 1.0" + '\n', ce);  
  36.           
  37.         buf.putString("startcty:" + flight.getStartCity() + '\n', ce);  
  38.           
  39.         buf.putString("endcity:" + flight.getEndCity() + '\n', ce);  
  40.           
  41.         buf.putString("flightway:" + flight.getFlightway() + '\n', ce);  
  42.           
  43.         buf.putString("date:" + flight.getDate() + '\n', ce);  
  44.           
  45.         buf.flip();  
  46.           
  47.         out.write(buf);  
  48.     }  
  49.   
  50. }  
package client;import java.nio.charset.Charset;import java.nio.charset.CharsetEncoder;import org.apache.mina.core.buffer.IoBuffer;import org.apache.mina.core.session.IoSession;import org.apache.mina.filter.codec.ProtocolEncoderAdapter;import org.apache.mina.filter.codec.ProtocolEncoderOutput;import domain.Flight;/** * @function :  * @author   :jy * @company  :万里网 * @date     :2011-8-7 */public class FlightClientEncoder extends ProtocolEncoderAdapter {	private final Charset charset;		public FlightClientEncoder(){		this.charset = Charset.forName("UTF-8");	}	@Override	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {		Flight flight = (Flight)message;				IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);				CharsetEncoder ce = charset.newEncoder();				buf.putString("Flight Search 1.0" + '\n', ce);				buf.putString("startcty:" + flight.getStartCity() + '\n', ce);				buf.putString("endcity:" + flight.getEndCity() + '\n', ce);				buf.putString("flightway:" + flight.getFlightway() + '\n', ce);				buf.putString("date:" + flight.getDate() + '\n', ce);				buf.flip();				out.write(buf);	}}

解码无需特殊处理,接收完数据直接向下传递

[java]
  1. package client;  
  2.   
  3. import java.nio.charset.Charset;  
  4. import java.nio.charset.CharsetDecoder;  
  5.   
  6. import org.apache.mina.core.buffer.IoBuffer;  
  7. import org.apache.mina.core.session.IoSession;  
  8. import org.apache.mina.filter.codec.CumulativeProtocolDecoder;  
  9. import org.apache.mina.filter.codec.ProtocolDecoderOutput;  
  10.   
  11. /** 
  12.  * @function :  
  13.  * @author   :jy 
  14.  * @company  :万里网 
  15.  * @date     :2011-8-7 
  16.  */  
  17. public class FlightClientDecoder extends CumulativeProtocolDecoder {  
  18.   
  19.     /* (non-Javadoc) 
  20.      * @see org.apache.mina.filter.codec.ProtocolDecoder#decode(org.apache.mina.core.session.IoSession, org.apache.mina.core.buffer.IoBuffer, org.apache.mina.filter.codec.ProtocolDecoderOutput) 
  21.      */  
  22.     @Override  
  23.     protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {  
  24.         CharsetDecoder cd = Charset.forName("UTF-8").newDecoder();  
  25.         IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);  
  26.           
  27.         while(in.hasRemaining()){  
  28.             buf.put(in.get());  
  29.         }  
  30.         buf.flip();  
  31.         out.write(buf.getString(cd));  
  32.         return false;  
  33.     }  
  34.   
  35. }  
package client;import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import org.apache.mina.core.buffer.IoBuffer;import org.apache.mina.core.session.IoSession;import org.apache.mina.filter.codec.CumulativeProtocolDecoder;import org.apache.mina.filter.codec.ProtocolDecoderOutput;/** * @function :  * @author   :jy * @company  :万里网 * @date     :2011-8-7 */public class FlightClientDecoder extends CumulativeProtocolDecoder {	/* (non-Javadoc)	 * @see org.apache.mina.filter.codec.ProtocolDecoder#decode(org.apache.mina.core.session.IoSession, org.apache.mina.core.buffer.IoBuffer, org.apache.mina.filter.codec.ProtocolDecoderOutput)	 */	@Override	protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {		CharsetDecoder cd = Charset.forName("UTF-8").newDecoder();		IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);				while(in.hasRemaining()){			buf.put(in.get());		}		buf.flip();		out.write(buf.getString(cd));		return false;	}}
客户端编解码工厂

[java]
  1. package client;  
  2.   
  3. import org.apache.mina.core.session.IoSession;  
  4. import org.apache.mina.filter.codec.ProtocolCodecFactory;  
  5. import org.apache.mina.filter.codec.ProtocolDecoder;  
  6. import org.apache.mina.filter.codec.ProtocolEncoder;  
  7.   
  8. /** 
  9.  * @function :  
  10.  * @author   :jy 
  11.  * @company  :万里网 
  12.  * @date     :2011-8-7 
  13.  */  
  14. public class FlightClientCodecFactory implements ProtocolCodecFactory {  
  15.     private final ProtocolEncoder encoder = new FlightClientEncoder();  
  16.     private final ProtocolDecoder decoder = new FlightClientDecoder();  
  17.       
  18.     /* (non-Javadoc) 
  19.      * @see org.apache.mina.filter.codec.ProtocolCodecFactory#getDecoder(org.apache.mina.core.session.IoSession) 
  20.      */  
  21.     @Override  
  22.     public ProtocolDecoder getDecoder(IoSession arg0) throws Exception {  
  23.         return decoder;  
  24.     }  
  25.   
  26.     /* (non-Javadoc) 
  27.      * @see org.apache.mina.filter.codec.ProtocolCodecFactory#getEncoder(org.apache.mina.core.session.IoSession) 
  28.      */  
  29.     @Override  
  30.     public ProtocolEncoder getEncoder(IoSession arg0) throws Exception {  
  31.         return encoder;  
  32.     }  
  33.   
  34. }  

转载地址:http://zyjdi.baihongyu.com/

你可能感兴趣的文章
VUE-Vue.js之$refs,父组件访问、修改子组件中 的数据
查看>>
Vue-子组件改变父级组件的信息
查看>>
Python自动化之pytest常用插件
查看>>
Python自动化之pytest框架使用详解
查看>>
【正则表达式】以个人的理解帮助大家认识正则表达式
查看>>
性能调优之iostat命令详解
查看>>
性能调优之iftop命令详解
查看>>
非关系型数据库(nosql)介绍
查看>>
移动端自动化测试-Windows-Android-Appium环境搭建
查看>>
Xpath使用方法
查看>>
移动端自动化测试-Mac-IOS-Appium环境搭建
查看>>
Selenium之前世今生
查看>>
Selenium-WebDriverApi接口详解
查看>>
Selenium-ActionChains Api接口详解
查看>>
Selenium-Switch与SelectApi接口详解
查看>>
Selenium-Css Selector使用方法
查看>>
Linux常用统计命令之wc
查看>>
测试必会之 Linux 三剑客之 sed
查看>>
Socket请求XML客户端程序
查看>>
Java中数字转大写货币(支持到千亿)
查看>>