日期:2014-05-17 浏览次数:20950 次
private static Logger logger = Logger.getLogger(Demo1Server.class); private static final int PORT = 3005; public static void main(String[] args) { IoAcceptor acceptor = new NioSocketAcceptor(); acceptor.addListener(new ServerListener()); acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new MyTextLineCodecFactory())); // 设置读取数据的缓冲区大小 acceptor.getSessionConfig().setReadBufferSize(2048); // 读写通道10秒内无操作进入空闲状态 acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); // 绑定逻辑处理起器 acceptor.setHandler(new Demo1ServerHandler()); // 绑定端口 try { acceptor.bind(new InetSocketAddress(PORT)); logger.info("服务器启动成功。。。。端口为:" + PORT); } catch (IOException e) { logger.error("服务器启动异常。。。。", e); e.printStackTrace(); } }
private Logger logger = Logger.getLogger(Demo2Client.class); private static final String HOST = "127.0.0.1"; private static final int PORT = 3005; public static void main(String[] args) { // 创建一个非阻塞的客户端程序 IoConnector connector = new NioSocketConnector(); // 设置连接超时时间 单位毫秒 connector.setConnectTimeout(30000); // 添加过滤器 connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new MyTextLineCodecFactory())); // 添加业务逻辑处理类 connector.setHandler(new Demo2ClientHandler()); // 创建连接 IoSession session = null; try { ConnectFuture connect = connector.connect(new InetSocketAddress( HOST, PORT)); // 等待连接创建完成 connect.awaitUninterruptibly(); // 获取session session = connect.getSession(); session.write("我爱你,mina!!!!"); } catch (Exception e) { System.out.println("客户端连接异常"); } session.getCloseFuture().awaitUninterruptibly(); connector.dispose(); }
private Logger logger = Logger.getLogger(MyTextLineCodecEncoder.class); //字符编码类型 private Charset charset = Charset.forName("UTF-8"); @Override public void dispose(IoSession arg0) throws Exception { } @Override public void encode(IoSession arg0, Object obj, ProtocolEncoderOutput out) throws Exception { logger.info("开始编码..........."); IoBuffer io = IoBuffer.allocate(100).setAutoExpand(true); CharsetEncoder ce = charset.newEncoder(); io.putString(obj.toString(), ce); io.put((byte)'\r'); io.put((byte)'\n'); io.flip(); out.write(io); }
private Logger logger = Logger.getLogger(MyTextLineCodecDecoder.class); //字符编码类型 private Charset charset = Charset.forName("UTF-8"); //设置数据存放的IoBuffer大小 private IoBuffer ioBuffer = IoBuffer.allocate(1024).setAutoExpand(true); @Override public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { logger.info("开始解码..........."); while(in.hasRemaining()){ byte by = in.get(); //将数据存放到IoBuffer中 ioBuffer.put(by); //数据解码结束标记 if(by == '\n'){ ioBuffer.flip(); byte