上节中通过一个简单的例子,对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 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 {
- }
- }
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 {
}
}
效果演示: