Android Mina通信 建立连接,发送和接收消息

mina简介:

名井南(Mina),1997年3月24日出生于美国德州圣安东尼奥,日本女歌手,韩国女子演唱组合TWICE成员。

mina百度抠图

一 下载mina 的jar包

下载地址

我下载的是mina-core-2.0.16.jar和slf4j-android-1.6.1-RC1.jar

二 服务端

1.启动服务,等待客户端连接:主要使用的类:NioSocketConnector

public class MinaService {

private NioSocketAcceptoracceptor =null;

public  void main() {

Log.i(BaseApp.TAG,"尝试启动服务器 ...: ");

// 继承IoService,服务器端接收器

        if (acceptor ==null) {

acceptor =new NioSocketAcceptor();

// 添加过滤器

            acceptor.getFilterChain().addLast("日志过滤器",new LoggingFilter());// 日志过滤器

            acceptor.getFilterChain().addLast("只能传输序列化后的对象",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));// 只能传输序列化后的对象

            acceptor.getFilterChain().addLast("threadPool",new ExecutorFilter(Executors.newCachedThreadPool()));

// 进行一些初始化配置

            acceptor.getSessionConfig().setReadBufferSize(2048*2);// 设置读缓存区大小

            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,10);// 如果10秒钟没有任何读写,就设置成空闲状态。 BOTH_IDLE(读和写)

            //设置Handler回调

            acceptor.setHandler(new MyHandler());

}

// 设置监听端口号,开始监听了

        try {

acceptor.bind(new InetSocketAddress(PORT));

Log.i(BaseApp.TAG,"启动成功: ");

}catch (Exception e) {

Log.i(BaseApp.TAG,"失败: "+e.getMessage());

e.printStackTrace();

}

}

}


2.MinaHandler 回调

public class MyHandler extends IoHandlerAdapter {

@Override

    public void exceptionCaught(IoSession session, Throwable cause)throws Exception {

super.exceptionCaught(session, cause);

Log.i(BaseApp.TAG,"exceptionCaught: ");

}

@Override

    public void inputClosed(IoSession session)throws Exception {

super.inputClosed(session);

Log.i(BaseApp.TAG,"inputClosed: ");

}

@Override

    public void sessionIdle(IoSession session, IdleStatus status)throws Exception {

super.sessionIdle(session, status);

Log.i(BaseApp.TAG,"sessionIdle: ");

}

// session创建时回调

    public void sessionCreated(IoSession session)throws Exception {

super.sessionCreated(session);

SessionManager.getInstance().setSession(session);

Log.i(BaseApp.TAG,"sessionCreated " );

}

// session打开时回调

    public void sessionOpened(IoSession session)throws Exception {

super.sessionOpened(session);

Log.i(BaseApp.TAG,"sessionOpened " );

}

// 消息接收时回调

    public void messageReceived(IoSession session, Object message)throws Exception {

super.messageReceived(session, message);

Log.i(BaseApp.TAG,"messageReceived: 接收到消息 =  "+message );

SessionManager.getInstance().upData(message+"");

}

// 消息发送时回调

    public void messageSent(IoSession session, Object message)throws Exception {

super.messageSent(session, message);

Log.i(BaseApp.TAG,"messageSent发送消息到服务端 =  "+message );

}

// session关闭时回调

    public void sessionClosed(IoSession session)throws Exception {

super.sessionClosed(session);

Log.i(BaseApp.TAG,"sessionClosed: 关闭session");

}

}

3.单例SessionManager ,setHanler()  需要在主页MainActivity写一个Handler并且设置过来  方便数据传递

public class SessionManager {

private IoSessionsession;

private static SessionManagerinstance =null;

private SessionManager(){

}

public static SessionManager getInstance() {

if (instance ==null) {

synchronized (SessionManager.class) {

if (instance ==null) {

instance =new SessionManager();

}

}

}

return instance;

}

public IoSession getSession() {

return session;

}

public void setSession(IoSession session) {

this.session = session;

}

private Handlerhandler;

public void setHandler(Handler handler){

this.handler = handler;

}

public void upData(String msg) {

Message message =new Message();

message.obj = msg;

handler.sendMessage(message);

}

/**

    * 写消息

    * */

    public void writeMag(String msg){

if(session !=null){

session.write(msg);

}

}

/**

    * 关闭

    * */

    public void closeSession(){

if(session !=null){

session.closeOnFlush();

session =null;

}

}

}

三:客户端

1.连接服务端


public class MinaConnectManager {

private static final StringTAG ="MinaConnectManager";

private NioSocketConnectorsocketConnector;

public MinaConnectManager() {

init();

}

private void init() {

socketConnector =new NioSocketConnector();

// 添加过滤器

        socketConnector.getFilterChain().addLast("日志过滤器",new LoggingFilter());// 日志过滤器

        socketConnector.getFilterChain().addLast("只能传输序列化后的对象",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));// 只能传输序列化后的对象

        //超时时间

        socketConnector.setConnectTimeoutMillis(5000);

// 回调的handler

        socketConnector.setHandler(new MinaHandler());

// 进行一些初始化配置

        socketConnector.getSessionConfig().setReadBufferSize(2048*2);// 设置读缓存区大小

        // 设置IP地址

        SocketAddress mAddress =new InetSocketAddress(LOCAL,PORT);

socketConnector.setDefaultRemoteAddress(mAddress);

}

public boolean connect() {

Log.i(TAG,"尝试连接: "+LOCAL);

try {

ConnectFuture connectFuture =socketConnector.connect();//查询连接状态

            connectFuture.awaitUninterruptibly();

IoSession mSession = connectFuture.getSession();

SessionManager.getInstance().setSession(mSession);//单例拿到实例用于发送消息

            Log.i(TAG,"连接成功: ");

return true;

}catch (Exception e) {

Log.i(TAG,"连接失败: "+e.getMessage());

e.printStackTrace();

return false;

}

}

}

2.Handler回调

public class MinaHandlerextends IoHandlerAdapter {

private static final StringTAG ="MinaHandler";

// session打开时回调

    public void sessionOpened(IoSession session)throws Exception {

super.sessionOpened(session);

Log.i(TAG,"sessionClosed: 连接打开");

}

@Override

    public void sessionClosed(IoSession session)throws Exception {

super.sessionClosed(session);

Log.i(TAG,"sessionClosed: 连接断开");

SessionManager.getInstance().upData("", Constants.CONNECT_ERR);

}

// 消息接收时回调

    public void messageReceived(IoSession session, Object message)throws Exception {

super.messageReceived(session, message);

Log.i(TAG,"messageReceived: 接收到消息");

SessionManager.getInstance().upData(message+"", Constants.DEVICE_MSG);

}

// 消息发送时回调

    public void messageSent(IoSession session, Object message)throws Exception {

super.messageSent(session, message);

Log.i(TAG,"messageSent: 发送消息成功");

}

@Override

    public void sessionIdle(IoSession session, IdleStatus status)throws Exception {

super.sessionIdle(session, status);

Log.i(TAG,"sessionIdle: 服务端空闲时间");

}

}

3.单例SessionManager    消息发送

public class SessionManager {

private IoSessionsession;

private volatile static SessionManagerinstance =null;

private SessionManager(){

}

public static SessionManager getInstance() {

if (instance ==null) {

synchronized (SessionManager.class) {

if (instance ==null) {

instance =new SessionManager();

}

}

}

return instance;

}

private Handlerhandler;

public void setHandler(Handler handler){

this.handler = handler;

}

public void upData(String msg,int what) {

Message message =new Message();

message.obj = msg;

message.what = what;

handler.sendMessage(message);

}

public IoSession getSession() {

return session;

}

public void setSession(IoSession session) {

this.session = session;

}

/**

    * 写消息

    * */

    public void writeMag(String msg){

if(session !=null){

session.write(msg);

}

}

/**

    * 关闭

    * */

    public void closeSession(){

if(session !=null){

session.closeOnFlush();

session =null;

}

}

}

四:注释基本都是有的,就不详细介绍了,百度很多介绍,客户端,服务端两边代码基本一样  只是一个启动服务等待连接  一个连接服务,代码基本就这么多,从项目重复制出来的,应该不差其它东西。


服务端


客户端连接


服务端建立连接

你可能感兴趣的:(Android Mina通信 建立连接,发送和接收消息)