Apache的Mina(Multipurpose Infrastructure Networked Applications)是一个网络应用框架,可以帮助用户开发高性能和高扩展性的网络应用程序;它提供
了一个抽象的、事件驱动的异步API,使Java NIO在各种传输协议(如TCP/IP,UDP/IP协议等)下快速高效开发。
简单实现:
client:
// 创建客户端连接器. NioSocketConnector connector = new NioSocketConnector(); connector.getFilterChain().addLast("logger", new LoggingFilter()); // 设置编码过滤器 connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset .forName("UTF-8")))); connector.setConnectTimeout(30); // 设置事件处理器 connector.setHandler(new ClientHandler()); // 建立连接 ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1", 9100)); // 等待连接创建完成 cf.awaitUninterruptibly(); // 发送消息 cf.getSession().write("hello"); // 等待连接断开 cf.getSession().getCloseFuture().awaitUninterruptibly(); connector.dispose();
server端:
IoAcceptor acceptor = new NioSocketAcceptor(); acceptor.getFilterChain().addLast("logger", new LoggingFilter()); // 指定编码过滤器 acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset .forName("UTF-8")))); // 指定业务逻辑处理器 acceptor.setHandler(new ServerHandler()); // 设置端口号 acceptor.setDefaultLocalAddress(new InetSocketAddress(9100)); // 启动监听 acceptor.bind(); server 处理器 class ServerHandler extends IoHandlerAdapter { @Override public void sessionCreated(IoSession session) { // 显示客户端的ip和端口 System.out .println(session.getRemoteAddress().toString() + " service"); } @Override public void messageReceived(IoSession session, Object message) throws Exception { String str = message.toString(); if (str.trim().equalsIgnoreCase("hello")) { // System.out.println(str + " client sent : hello"); // 结束会话 session.close(); return; } Date date = new Date(); // 返回当前时间的字符串 session.write(date.toString()); } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/11027.html