- package com.allinpay.mina;
- import java.io.IOException;
- import java.net.InetSocketAddress;
- import org.apache.mina.common.IoAcceptor;
- import org.apache.mina.filter.codec.ProtocolCodecFilter;
- import org.apache.mina.transport.socket.nio.SocketAcceptor;
- import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;
- public class MyServer {
- /*服务器监听端口*/
- private int SERVER_PORT = 10000;
- private IoAcceptor acceptor=null;
- /**
- * 接收报文的服务端Socket的idle时间(秒)
- */
- public static int Server_Session_IdleSec = 5*60;
- /**
- * 构造函数,创建服务器监听线程
- * @param aServerPort
- * @throws IOException
- */
- public MyServer(int aServerPort) throws IOException {
- SERVER_PORT=aServerPort;
- connect();
- }
- /**
- * 创建服务器监听线程
- * @throws IOException
- *
- */
- public void connect() throws IOException{
- close();
- acceptor = new SocketAcceptor();
- SocketAcceptorConfig cfg = new SocketAcceptorConfig();
- cfg.setReuseAddress(true);
- /**
- * 添加×××
- */
- cfg.getFilterChain()
- .addLast("codec",new ProtocolCodecFilter(new MyCodecFactory()));
- /**
- * 添加系统日志
- */
- //cfg.getFilterChain().addLast("logger", new LoggingFilter());
- /**
- * 建立服务器监听
- */
- acceptor.bind(new InetSocketAddress(SERVER_PORT),new MyServerIoSessionHandler(this), cfg);
- // LoggerUtil.info("Server start on port " + SERVER_PORT);
- }
- /**
- * 关闭连接
- * @return
- */
- public boolean close(){
- if(null != acceptor){
- acceptor.unbindAll();
- acceptor=null;
- }
- return true;
- }
- public static void main(String[] args){
- try {
- new MyServer(10000);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- package com.allinpay.mina;
- import java.io.IOException;
- import org.apache.mina.common.IdleStatus;
- import org.apache.mina.common.IoHandlerAdapter;
- import org.apache.mina.common.IoSession;
- /**
- * Mina框架定义的ServerSessionHandler
- */
- public class MyServerIoSessionHandler extends IoHandlerAdapter {
- /**
- * 服务器线程
- */
- private MyServer server_channel = null;
- /**
- * 构造函数
- *
- * @param channel
- * 服务器线程
- */
- public MyServerIoSessionHandler(MyServer channel) {
- super();
- server_channel = channel;
- }
- /**
- * 服务器socket的session打开时触发该方法,设置服务器的idle时间(5分钟)
- */
- public void sessionOpened(IoSession session) {
- // 设置服务器idle时间
- session.setIdleTime(IdleStatus.READER_IDLE,
- MyServer.Server_Session_IdleSec);
- }
- /**
- *
- */
- public void messageReceived(IoSession session, Object message) {
- String orderMsg = (String) message;
- System.out.println(orderMsg);
- // if(null == orderMsg){//表示空闲报文,直接返回,不需要做后续处理
- // // LoggerUtil.info("messageReceived message is null ");
- // return;
- // }
- session.write(orderMsg);
- }
- public void sessionIdle(IoSession session, IdleStatus status)
- throws IOException {
- // disconnect an idle client
- session.close();
- server_channel.connect();
- }
- public void exceptionCaught(IoSession session, Throwable cause)
- throws IOException {
- // SessionLog.info(session,cause.getMessage());
- // disconnect an idle client
- session.close();
- server_channel.connect();
- }
- }
- package com.allinpay.mina;
- import org.apache.mina.filter.codec.ProtocolCodecFactory;
- public class MyCodecFactory implements ProtocolCodecFactory {
- private final MyEncoder encoder;
- private final MyDecoder decoder;
- public MyCodecFactory() {
- encoder = new MyEncoder();
- decoder = new MyDecoder();
- }
- public MyEncoder getEncoder() {
- return encoder;
- }
- public MyDecoder getDecoder() {
- return decoder;
- }
- }
- package com.allinpay.mina;
- import java.io.IOException;
- import org.apache.mina.common.ByteBuffer;
- import org.apache.mina.common.IoSession;
- import org.apache.mina.filter.codec.ProtocolDecoderAdapter;
- import org.apache.mina.filter.codec.ProtocolDecoderOutput;
- public class MyDecoder extends ProtocolDecoderAdapter {
- public void decode(IoSession session, ByteBuffer buf,ProtocolDecoderOutput out) throws Exception {
- // LoggerUtil.info("GtsMessageDecoder start ");
- try{
- String request = recv(buf);
- // SpdbRequestParser requestParser = new SpdbRequestParser();
- // requestParser.initByXml(request);
- out.write(request);
- }catch (Exception e) {
- // LoggerUtil.error(e);
- throw e;
- }
- // LoggerUtil.info("GtsMessageDecoder End ");
- }
- private String recv(ByteBuffer buf) throws IOException{
- byte[] b=new byte[buf.limit()];
- buf.get(b);
- // LoggerUtil.info("recv string["+new String(b,"GBK")+"], length :"+b.length);
- byte[] head = new byte[64];
- System.arraycopy(b, 0, head, 0, 64);
- String headstring = new String(head);
- // LoggerUtil.info("recv head["+headstring+"]");
- int length = Integer.parseInt(headstring.substring(8,16).trim());
- // LoggerUtil.info("recv body length["+length+"]");
- byte[] body = new byte[length];
- System.arraycopy(b, 64, body, 0, length);
- // LoggerUtil.info("recv body ["+new String(body,"GBK")+"]");
- return new String(body,"GBK");
- }
- }
- package com.allinpay.mina;
- import org.apache.mina.common.ByteBuffer;
- import org.apache.mina.common.IoSession;
- import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
- import org.apache.mina.filter.codec.ProtocolEncoderOutput;
- public class MyEncoder extends ProtocolEncoderAdapter {
- public MyEncoder() {
- }
- public void encode(IoSession session, Object message,
- ProtocolEncoderOutput out) throws Exception {
- // LoggerUtil.info("GtsMessageEncoder start ");
- try{
- // LoggerUtil.info("message " + message);
- String response = (String)message;
- // LoggerUtil.debug("Encode message : " + xml);
- byte[] bt = response.getBytes("GBK");
- ByteBuffer buf = ByteBuffer.allocate(bt.length).setAutoExpand(true);
- buf.put(bt);
- buf.flip();
- out.write(buf);
- }catch (Exception e) {
- // LoggerUtil.error("GtsMessageEncoder Error",e);
- }
- // LoggerUtil.info("GtsMessageEncoder End ");
- }
- // public byte[] send(byte[] data,String Fund_Id,String Trade_Code) throws IOException {
- // byte[] gbkData = new String(data,"UTF-8").getBytes("GBK");
- // String h1_7 =Fund_Id;//Char(7)
- // String h8="0";//Char(1)
- // String h9_16=" "; //Char(8)
- // String h17_24 =" "+Trade_Code; //Char(8)
- // String h25_32 = "00000000"; //Char(8)
- // String h33_64 = "00000000000000000000000000000000"; //Char(32)
- // h9_16=h9_16+gbkData.length;
- // String head = h1_7 + h8+h9_16.substring(h9_16.length()-8)+h17_24.substring(h17_24.length()-8)+h25_32+h33_64;
- // String str = head+new String(gbkData,"GBK");
- // return str.getBytes("GBK");
- // }
- }
转载于:https://blog.51cto.com/steveskylook/760888