• Mina使用总结(四)传输对象ObjectSerializationCodecFactory


    用mina框架传输对象,对于开发者来说,直接传输对象,而不用自己编写相应的报文转换代码,将大大节省

    开发时间。

    即使用对象编码解码器

    使用ObjectSerializationCodecFactory

    服务端

    MinaServer.java代码如下

    package com.bypay.mina.server;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.SocketAddress;
    import java.util.HashSet;
    import java.util.Set;
    import java.util.concurrent.Executors;
    import org.apache.mina.core.service.IoAcceptor;
    import org.apache.mina.core.session.IdleStatus;
    import org.apache.mina.filter.codec.ProtocolCodecFilter;
    import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
    import org.apache.mina.filter.executor.ExecutorFilter;
    import org.apache.mina.filter.logging.LoggingFilter;
    import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
    
    import com.bypay.mina.server.handle.ObjectHandler;
    
    public class MinaServer {
    
        private IoAcceptor acceptor ;
        
        public MinaServer() {
            acceptor = new NioSocketAcceptor();
            //设置日志过滤器
            acceptor.getFilterChain().addLast("logger", new LoggingFilter());
            //设置编码器
            acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
            acceptor.getFilterChain().addLast("threadPool",new ExecutorFilter(Executors.newCachedThreadPool()));
            //设置读缓冲
            acceptor.getSessionConfig().setReadBufferSize(2048*2048);
            //设置心跳频率
            acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 30);
            //设置Handler
            acceptor.setHandler(new ObjectHandler());
            try {
                Set<SocketAddress> addresses = new HashSet<SocketAddress>();
                //此处的host地址需注意,需要填写主机对外的ip地址或域名,不可用localhost
                addresses.add(new InetSocketAddress("localhost", 18886));
                acceptor.bind(addresses);
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            System.out.println("--------------------------------------------------");
            System.out.println("Server Started");
            System.out.println("--------------------------------------------------");
        }
        
        public static void main(String[] args) {
            MinaServer server = new MinaServer();
            
        }
    }

    ObjectHandler.java

    package com.bypay.mina.server.handle;
    
    import org.apache.mina.core.service.IoHandlerAdapter;
    import org.apache.mina.core.session.IdleStatus;
    import org.apache.mina.core.session.IoSession;
    import com.bypay.mina.bean.TransInfo;
    
    public class ObjectHandler extends IoHandlerAdapter {
        
    
        @Override
        public void sessionCreated(IoSession session) {
            //session创建时回调
            System.out.println("Session Created!");
        }
    
        @Override
        public void sessionClosed(IoSession session) throws Exception {    
            //session关闭时回调
            System.out.println("Session Closed!");
        }
    
        @Override
        public void sessionOpened(IoSession session) throws Exception {
            //session打开时回调
            System.out.println("Session Opened!");
        }
    
        @Override
        public void sessionIdle(IoSession session, IdleStatus status) {
            //心跳
            System.out.println("sessionIdle");
        }
    
        @Override
        public void exceptionCaught(IoSession session, Throwable cause) {
            //异常时回调
            cause.printStackTrace();
            //关闭session
            session.close(true);
        }
    
        @Override
        public void messageReceived(IoSession session, Object message)
                throws Exception {
            //接收消息
           //TransInfo为自定义对象
            TransInfo info = (TransInfo) message;        
            //System.out.println("接收返回消息成功");        
            //System.out.println("id:"+info.getId());    
            //System.out.println("msg:"+info.getMsg());
            //Thread.sleep(100);
            session.write(info);
            //session.close(true);
        }
    }

    TransInfo.java

    传输的自定义对象必须实现Serializable接口,且客户端和服务端的包名+类名必须要保持一致

    package com.bypay.mina.bean;
    
    public class TransInfo implements java.io.Serializable{
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    
        private long id;
        
        private String msg;
    
        public long getId() {
            return id;
        }
    
        public void setId(long id) {
            this.id = id;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
        
        
    }

    客户端

    客户端必须也要设置同样的编码和解码工厂ObjectSerializationCodecFactory

    如MinaClient.java

    package com.bypay.mina.client;
    
    import java.net.InetSocketAddress;
    import org.apache.mina.core.future.ConnectFuture;
    import org.apache.mina.core.session.IoSession;
    import org.apache.mina.filter.codec.ProtocolCodecFilter;
    import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
    import org.apache.mina.filter.logging.LoggingFilter;
    import org.apache.mina.transport.socket.nio.NioSocketConnector;
    import com.bypay.mina.handler.MyClientHandler;
    
    /**
     * Mina客户端
     * @author 唐延波
     * @date 2015-1-20
     *
     */
    public class MinaClient {
        
        private static int CONNECT_TIMEOUT = 1000;
    
        private static String HOSTNAME = "localhost";
    
        private static int PORT = 18886;
    
        /**
         * @author 唐延波
         * @throws InterruptedException
         * @date 2014-11-4
         */
        public static void main(String[] args) throws InterruptedException {
            NioSocketConnector connector = new NioSocketConnector();
            connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
            //设置读缓冲,传输的内容必须小于此缓冲
            connector.getSessionConfig().setReadBufferSize(2048*2048);
            //设置编码解码器
            connector.getFilterChain().addLast("codec",
                    new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
            //设置日志过滤器
            connector.getFilterChain().addLast("logger", new LoggingFilter());
            //设置Handler
            connector.setHandler(new MyClientHandler());
    
            //获取连接,该方法为异步执行
            ConnectFuture future = connector.connect(new InetSocketAddress(
                    HOSTNAME, PORT));
            //等待连接建立
            future.awaitUninterruptibly();
            //获取session
            IoSession session = future.getSession();
    
            //等待session关闭
            session.getCloseFuture().awaitUninterruptibly();
            //释放connector
            connector.dispose();
    
        }
    }

    MyClientHandler.java

    package com.bypay.mina.handler;
    
    import org.apache.mina.core.service.IoHandlerAdapter;
    import org.apache.mina.core.session.IdleStatus;
    import org.apache.mina.core.session.IoSession;
    
    import com.bypay.mina.bean.TransInfo;
    
    /**
     * ClientHandler
     * @author 唐延波
     * @date 2015-1-20
     *
     */
    public class MyClientHandler extends IoHandlerAdapter {
    
        @Override
        public void sessionCreated(IoSession session) throws Exception {
            //session 创建时调用
            TransInfo info = new TransInfo();
            session.write(info);
        }
    
        @Override
        public void messageReceived(IoSession session, Object message)
                throws Exception {
            //异步接收消息
            TransInfo info = (TransInfo) message;
            session.close(true);
        }
    
        @Override
        public void exceptionCaught(IoSession session, Throwable cause)
                throws Exception {
            //出现异常
            cause.printStackTrace();
            session.close(true);
        }
    
        @Override
        public void sessionIdle(IoSession session, IdleStatus status)
                throws Exception {
            //心跳
            System.out.println("客户端ide:");
        }
    }
  • 相关阅读:
    Spring MVC的Controller统一异常处理:HandlerExceptionResolver
    Log4j按级别输出日志到不同文件配置
    Linux top命令用法
    free -m内存使用详解
    Linux运维中遇到的常见问题
    ubuntu16.04 nginx安装
    redis主从配置及主从切换
    Redis持久化配置-AOF
    如何处理消极想法
    libevent安装总结
  • 原文地址:https://www.cnblogs.com/tangyanbo/p/4297553.html
Copyright © 2020-2023  润新知