上节中通过一个简单的例子,对Mina框架有了大体的了解,在上节的基础上,看看怎样实现客户端与服务端的通信,
废话不多说了,直接看代码:
public class Test {
public static void main(String[] args) throws Exception{
SocketConnector connector = new NioSocketConnector();
IoFilter filter = new ProtocolCodecFilter(new TextLineCodecFactory());
connector.getFilterChain().addLast("vestigge", filter);
SocketAddress soketAddress = new InetSocketAddress("127.0.0.1", 5469);
connector.setHandler(new ClientHandler());
ConnectFuture future= connector.connect(soketAddress);
future.join();
if (!future.isConnected()) {
System.out.println("连接服务器失败");
return;
}
future.getSession().write("hello");
}
}
可以看到代码与服务器端的代码很像,也是非常的简单,这就是框架的好处,不用再重复发明轮子,省了不少事,
public class ClientHandler extends IoHandlerAdapter {
public void messageReceived(IoSession arg0, Object message) throws Exception {
System.out.println("收到服务器消息:" + message.toString());
}
public void exceptionCaught(IoSession arg0, Throwable arg1)
throws Exception {
}
}
效果演示:

本文通过一个简单示例展示了如何使用Mina框架实现客户端与服务端之间的通信。客户端代码与服务器端类似,通过NioSocketConnector建立连接,并使用TextLineCodecFactory进行编解码。当接收到服务器消息时,ClientHandler将输出接收到的消息。
1万+

被折叠的 条评论
为什么被折叠?



