1.先创建一个MinaService,在里面配置NioSocketConnector,创建客户端IoClientHandler
connector = new NioSocketConnector(); connector.setConnectTimeoutMillis(ConnectUtils.TIMEOUT); connector.getSessionConfig().setUseReadOperation(true); connector.getSessionConfig().setReadBufferSize(2048 * 2048); connector.getFilterChain().addLast("mycoder", new ProtocolCodecFilter(new ByteArrayCodecFactory(Charset.forName("gb2312")))); connector.setHandler(new IoClientHandler());
2.连接服务端
ConnectFuture future = connector.connect(new InetSocketAddress(ConnectUtils.HOST, ConnectUtils.PORT)); future.awaitUninterruptibly(); session = future.getSession(); if (session.isConnected()) { System.out.println(ConnectUtils.stringNowTime() + " : 客户端连接服务器成功....."); break; }
3.添加监听
connector.addListener(new HeartBeatListener(connector));
4.在IoClientHandler中的MessageReceived接收服务端发过来的数据
public void messageReceived(IoSession session, Object message) throws Exception {5.需要将message转换
public String formatHeapBuffer(IoBuffer ioBuffer) { byte[] b = new byte[ioBuffer.limit()]; ioBuffer.get(b); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < b.length; i++) { buffer.append((char) b[i]); } return buffer.substring(0, buffer.length() - 1); }
6.拿到数据可以通过Messenger发送数据到Activity中
7.断线重连,一般会调用
public void sessionDestroyed(IoSession arg0) {
只需要在这个方法中执行重练操作就OJBK了.