[Java教程]Mina框架HelloWorld入门
0
2013-03-13 02:00:09
首先推荐几篇Mina框架的好文章:
Mina框架研究(1)
Mina框架研究(2)
Mina框架研究(3)
Mina框架的依赖包在Mina官网下载:http://mina.apache.org/
Mina第一个HelloWorld程序:
服务端程序:
Minaserver.java:1 public class MinaServer { 2 private IoAcceptor ioAcceptor; 3 4 public MinaServer(int port) 5 { 6 ioAcceptor = new NioSocketAcceptor(); 7 try { 8 //设置处理器 9 ioAcceptor.setHandler(new MyHandler());10 //绑定端口11 ioAcceptor.bind(new InetSocketAddress(port));12 //规定协议,设定过滤,这里用TextLineCodecFactory文本协议13 ioAcceptor.getFilterChain().addLast("test", new ProtocolCodecFilter(new TextLineCodecFactory()));14 } catch (IOException e) {15 e.printStackTrace();16 }17 }18 }
MyHandler.java: (服务端接收消息后的业务逻辑处理)1 public class MyHandler extends IoHandlerAdapter {2 /**接收到信息后进行逻辑处理*/3 @Override4 public void messageReceived(IoSession session, Object message)5 throws Exception {6 String getmessage = message.toString();7 System.out.println(getmessage);8 }9 }
客户端程序:
MinaClient.java:1 public class MinaClient { 2 private IoConnector ioConnector; 3 4 public MinaClient(String host, int port) 5 { 6 ioConnector = new NioSocketConnector(); 7 //过滤信息,封装成文本格式输出 8 ioConnector.getFilterChain().addLast("test", new ProtocolCodecFilter(new TextLineCodecFactory())); 9 10 ioConnector.setHandler(new ClientHandler("Hello world!"));11 ioConnector.connect(new InetSocketAddress(host, port));12 }13 }
ClientHandler.java:
1 public class ClientHandler extends IoHandlerAdapter { 2 //发送给服务端的消息 3 private String sendToServer; 4 5 public ClientHandler(String words) 6 { 7 sendToServer = words; 8 } 9 10 @Override11 public void sessionOpened(IoSession session) throws Exception {12 session.write(sendToServer);13 }14 }
本文网址:http://www.shaoqun.com/a/55776.html
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。
0