服务端:
package com.newyulong.upm.testmina; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; import mina.client.normal.ClientProtocolCodecFactory; import org.apache.mina.core.filterchain.IoFilter; import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; import org.apache.mina.transport.socket.nio.NioSocketConnector; public class MainFrame { private static final int PORT = 5469; public static void main(String[] args) throws IOException { //创建主机对象 IoAcceptor acceptor = new NioSocketAcceptor(); //IoFilter filter = new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName( "UTF-8"))); //acceptor.getFilterChain().addLast("vestigge", filter); //设置业务处理 acceptor.setHandler(new ServerHandler()); ClientProtocolCodecFactory cpcf = new ClientProtocolCodecFactory(); acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(cpcf)); //设置编码过滤器 //绑定地址 acceptor.bind(new InetSocketAddress(PORT)); System.out.println("服务器正在监听端口" + PORT +"..."); } }
服务端业务处理类:
package com.newyulong.upm.testmina; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IoSession; public class ServerHandler extends IoHandlerAdapter { public void messageReceived(IoSession session, Object message) throws Exception { System.out.println("收到客户端消息:" + message.toString()); // 服务端发送数据到客户端 sendMsgToClient(session); } @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { System.out.println("服务器出现异常:" +cause); } public void sessionCreated(IoSession session) throws Exception { System.out.println("========sessionCreated=========="); } public void sendMsgToClient(IoSession session) throws IOException { // 服务端发送数据到客户端 System.out.println("服务端say:"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(System.in)); String inString = bufferedReader.readLine(); session.write(inString); if (inString.equals("quit")) { session.close(true); } } }
客户端:
加码和解码的工厂类
package mina.client.normal; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFactory; public class ClientProtocolCodecFactory implements ProtocolCodecFactory { private ProtocolEncoder protocolEncoder; private ProtocolDecoder protocolDecoder; public ProtocolEncoder getEncoder(IoSession session) throws Exception { // TODO Auto-generated method stub return protocolEncoder; } public ProtocolDecoder getDecoder(IoSession session) throws Exception { // TODO Auto-generated method stub return protocolDecoder; } public ClientProtocolCodecFactory(){ this.protocolEncoder = new ProtocolEncoder(); this.protocolDecoder = new ProtocolDecoder(); } }
具体的加码的处理类
package mina.client.normal; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderAdapter; import org.apache.mina.filter.codec.ProtocolEncoderOutput; public class ProtocolEncoder extends ProtocolEncoderAdapter { public void encode(IoSession ioSession, Object o, ProtocolEncoderOutput protocolEncoderOutput) throws Exception { System.out.println("输出字符串:" + new String(o.toString().getBytes())); String message = (String)o; IoBuffer buf = IoBuffer.allocate(1000); buf.setAutoExpand(true); buf.put(message.getBytes("UTF-8")); buf.flip(); System.out.println("enter in encoder ........"); // buf.asCharBuffer(); protocolEncoderOutput.write(buf); } }
解码的处理类
package mina.client.normal; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import com.kms.components.io.dto.IMessage; public class ProtocolDecoder extends CumulativeProtocolDecoder { @Override protected boolean doDecode(IoSession arg0, IoBuffer arg1, ProtocolDecoderOutput arg2) throws Exception { byte[] returnString = arg1.array(); System.out.println(new String(returnString)); int limit = arg1.limit(); byte[] data = new byte[limit]; arg1.get(data); System.out.println(data); String returnTyped = new String(data); System.out.println("mmm:" + returnTyped); arg2.write(returnTyped); return true; } }
客户端处理业务类:
package mina.client.normal;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
public class TimeClientHandler extends IoHandlerAdapter {
public TimeClientHandler() {
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
System.out.println("客户端接受到数据:" + message);// 显示接收到的消息
}
//客户端创建会话
public void sessionCreated(IoSession session) throws Exception {
System.out.println("会话创建");
session.write("client session create");
// Empty handler
}
}
测试类
package mina.client.normal; import java.net.InetSocketAddress; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.future.ReadFuture; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.transport.socket.nio.NioSocketConnector; public class ClientTest { public static void main(String[] args) { //定义客户端 NioSocketConnector nc = new NioSocketConnector(); InetSocketAddress address = new InetSocketAddress("127.0.0.1", 5469); TimeClientHandler tch = new TimeClientHandler(); ClientProtocolCodecFactory cpcf = new ClientProtocolCodecFactory(); nc.getFilterChain().addLast("codec", new ProtocolCodecFilter(cpcf)); //设置编码过滤器 nc.setHandler(tch); /** //换一种方法 此种方式可以加载多个过滤器 /** DefaultIoFilterChainBuilder dcb = new DefaultIoFilterChainBuilder(); Map map = new LinkedHashMap(); map.put("codecFilter", new ProtocolCodecFilter(cpcf)); dcb.setFilters(map); nc.setFilterChainBuilder(dcb); **/ ConnectFuture cf = nc.connect(address); cf.awaitUninterruptibly();//等待连接创建完成 IoSession session = cf.getSession(); session.write("hello");//发送消息 //cf.getSession().write("quit");//发送消息 session.getConfig().setUseReadOperation(true); // 客户端开始读取数据 ReadFuture readFuture = session.read(); readFuture.awaitUninterruptibly(); Object respData = readFuture.getMessage(); session.getCloseFuture().awaitUninterruptibly();//等待连接断开 System.out.println("客户端读取数据:" + (String)respData); } }