Android 简单使用mina传递byte数组

具体使用的包可以参考http://www.2cto.com/kf/201606/515499.html,感谢作者的帮助



如果是在eclipse上,直接导入log4j-1.2.17.jar,mina-core-2.0.0.jar slf4j-api-1.5.11.jar slf4j-simple-1.5.2.jar这几个包就可以

如果实在Android studio上编辑,就需要做些修改了

第一步:

把jar包拷贝到对应的mudule下的libs文件夹

第二步:

module关联jar包(如果不会可以查查百度怎么关联,这时候会有些错误,比如jar包内容重复,可以删除掉log4j-1.2.17.jar包,这个是日志包,没有影响


第三步:在对应的module的gradle添加

    defaultConfig {
        multiDexEnabled true
    }



这时候android studio的mina包算是基本导入了


对于参考的文章,他给出的编解码工厂是出来字符串的,需要在服务器发送字符串时候就要带上换行回车符,但是我们要我使用的是字节数组,需要自己定制

顺便封装了一下,可以直接放到工程中使用,最好还是自己去看看手册,会收获更多

package com.example.sockettext;

import java.net.InetSocketAddress;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.service.IoService;
import org.apache.mina.core.service.IoServiceListener;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderAdapter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.transport.socket.nio.NioSocketConnector;


import android.util.Log;

public class SocketUtils{
	private MinaThread socketRun;
	private IoSession session;
	private SocketUtilsListener mSocketUtilsListener;
	private String ip;
	private int port;

	public SocketUtils(String ip, int port){
		this.ip = ip;
		this.port = port;
	}

	//创建连接线程
	public Runnable connect(){
		socketRun = new MinaThread(ip, port);
		return socketRun;
	}


	//写入byte数组
	public void write(byte[] data){
		if (session != null){
			session.write(IoBuffer.wrap(data));//关键,传递数组的关键
		}else{
			SocketUtilsLog("write:" + new String(data) + "出错");
		}
	}

	//是否连接状态
	public boolean isConnect(){
		if (session == null){
			return false;
		}
		return session.isConnected();
	}

	public void close(){
		if (session == null){
			return;
		}
		session.close();
	}

	//设置监听器
	void setSocketUtilsListener(SocketUtilsListener l){
		mSocketUtilsListener = l;
	}

	//自定义log
	void SocketUtilsLog(String str){
		Log.e("SocketUtilsLog", str);
	}


	public interface SocketUtilsListener{
		void sendOK();
		void ReceiveData(byte[]data);
		void disConnect();
		void connectOk();
		void connectErr(Exception e);
	}

	class MinaThread implements Runnable{
		private int port;
		private String ip;
		MinaThread(String ip, int port){
			this.ip = ip;
			this.port = port;
		}
		@Override
		public void run() {
			IoConnector connector = new NioSocketConnector();
			//设置链接超时时间
			connector.setConnectTimeoutMillis(30000);
			connector.getFilterChain().addLast("codec",
					new ProtocolCodecFilter(new ByteArrayCodecFactory()));
			connector.setHandler(new MinaClientHandler());
			connector.addListener(new IoServiceListener() {

				@Override
				public void sessionDestroyed(IoSession arg0) throws Exception {
					SocketUtilsLog("sessionDestroyed");
					if (mSocketUtilsListener != null){
						mSocketUtilsListener.disConnect();
					}
				}

				@Override
				public void sessionCreated(IoSession arg0) throws Exception {
					SocketUtilsLog("sessionCreated");
					if(mSocketUtilsListener != null){
						mSocketUtilsListener.connectOk();
					}
				}

				@Override
				public void serviceIdle(IoService arg0, IdleStatus arg1) throws Exception {
				}
				@Override
				public void serviceDeactivated(IoService arg0) throws Exception {
				}
				@Override
				public void serviceActivated(IoService arg0) throws Exception {
				}
			});
			try{
				ConnectFuture future = connector.connect(new InetSocketAddress(ip, port));//创建链接
				future.awaitUninterruptibly();// 等待连接创建完成
				session = future.getSession();
//				session.write(IoBuffer.wrap("start".getBytes()));
			}catch (Exception e){
				SocketUtilsLog("客户端链接异常..." + e.toString());
				if (mSocketUtilsListener != null){
					mSocketUtilsListener.connectErr(e);
				}
			}
		}
	}


	public class MinaClientHandler extends IoHandlerAdapter {
		@Override
		public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
			SocketUtilsLog("客户端发生异常" + cause.getMessage());
			if (mSocketUtilsListener != null){

			}
			super.exceptionCaught(session, cause);
		}

		@Override
		public void messageReceived(IoSession session, Object message) throws Exception {
			byte[] bytes = (byte[])message;
//	        Log.e("messageReceived", "客户端接收到的信息为:" + new String (bytes));
			if (mSocketUtilsListener != null){
				mSocketUtilsListener.ReceiveData(bytes);
			}
			super.messageReceived(session, message);
		}

		@Override
		public void messageSent(IoSession session, Object message) throws Exception {
			super.messageSent(session, message);
		}
	}
	//编码
	public class ByteArrayEncoder extends ProtocolEncoderAdapter {

		@Override
		public void encode(IoSession session, Object message,
						   ProtocolEncoderOutput out){
			out.write(message);
			out.flush();
		}
	}
	//解码
	public class ByteArrayDecoder extends ProtocolDecoderAdapter {
		@Override
		public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
				throws Exception {
			int limit = in.limit();
			byte[] bytes = new byte[limit];
			in.get(bytes);
			out.write(bytes);
		}
	}

	//工厂
	public class ByteArrayCodecFactory implements ProtocolCodecFactory {
		private ByteArrayDecoder decoder;
		private ByteArrayEncoder encoder;
		public ByteArrayCodecFactory() {
			encoder = new ByteArrayEncoder();
			decoder = new ByteArrayDecoder();
		}
		@Override
		public ProtocolDecoder getDecoder(IoSession session) throws Exception {
			return decoder;
		}
		@Override
		public ProtocolEncoder getEncoder(IoSession session) throws Exception {
			return encoder;
		}
	}

}










你可能感兴趣的:(Android 简单使用mina传递byte数组)