mina之基本使用

来源:互联网 发布:ce修改器6.5源码 编辑:程序博客网 时间:2024/05/22 08:05

mina之基本使用

原创 2017年04月27日 20:24:23

创建服务端程序

  • 相关依赖包
<dependency>    <groupId>org.apache.mina</groupId>    <artifactId>mina-core</artifactId>    <version>2.0.16</version></dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 服务端程序
package com.mina.server;import org.apache.mina.core.service.IoAcceptor;import org.apache.mina.core.service.IoHandlerAdapter;import org.apache.mina.core.session.IdleStatus;import org.apache.mina.core.session.IoSession;import org.apache.mina.filter.codec.ProtocolCodecFilter;import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;import org.apache.mina.filter.logging.LoggingFilter;import org.apache.mina.transport.socket.nio.NioSocketAcceptor;import java.net.InetSocketAddress;import java.util.Date;public class MinaService {    public static void main(String[] args) {        IoAcceptor acceptor = new NioSocketAcceptor();        //添加日志过滤器        acceptor.getFilterChain().addLast("logger", new LoggingFilter());        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));        acceptor.setHandler(new DemoServerHandler());        acceptor.getSessionConfig().setReadBufferSize(2048);        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);        try {            acceptor.bind(new InetSocketAddress(9555));        } catch (Exception e) {            e.printStackTrace();        }        System.out.println("启动服务。。。。");    }    /**     * @ClassName: DemoServerHandler     * @Description: 负责session对象的创建和监听以及消息的创建和接收监听     */    private static class DemoServerHandler extends IoHandlerAdapter{        //服务器与客户端创建连接        @Override        public void sessionCreated(IoSession session) throws Exception {            System.out.println("服务器与客户端创建连接...");            super.sessionCreated(session);        }        @Override        public void sessionOpened(IoSession session) throws Exception {            System.out.println("服务器与客户端连接打开...");            super.sessionOpened(session);        }        //消息的接收处理        @Override        public void messageReceived(IoSession session, Object message)                throws Exception {            // TODO Auto-generated method stub            super.messageReceived(session, message);            String str = message.toString();            Date date = new Date();            session.write(date.toString());            System.out.println("接收到的数据:"+str);        }        @Override        public void messageSent(IoSession session, Object message)                throws Exception {            // TODO Auto-generated method stub            super.messageSent(session, message);        }        @Override        public void sessionClosed(IoSession session) throws Exception {            // TODO Auto-generated method stub            super.sessionClosed(session);        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79

安卓端代码

  • MainActivity
package com.mina;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.net.wifi.WifiInfo;import android.net.wifi.WifiManager;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v4.content.LocalBroadcastManager;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.util.Log;import android.view.View;import android.view.Menu;import android.view.MenuItem;import android.widget.Button;import android.widget.TextView;public class MainActivity extends AppCompatActivity {    private MessageBroadcastReceiver receiver;    private TextView mTextView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)                        .setAction("Action", null).show();            }        });        mTextView = (TextView) findViewById(R.id.text);        Button button1 = (Button) findViewById(R.id.btn1);        button1.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Log.e("tag", "点击启动服务");                Intent intent = new Intent(MainActivity.this, MinaService.class);                startService(intent);            }        });        Button button2 = (Button) findViewById(R.id.btn2);        button2.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Log.e("tag", "点击发送消息");                SessionManager.getInstance().writeToServer(mTextView.getText());            }        });        //获取wifi服务        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);        //判断wifi是否开启        if (!wifiManager.isWifiEnabled()) {            wifiManager.setWifiEnabled(true);        }        WifiInfo wifiInfo = wifiManager.getConnectionInfo();        int ipAddress = wifiInfo.getIpAddress();        String ip = intToIp(ipAddress);        mTextView.setText(ip);        registerBroadcast();    }    private String intToIp(int i) {        return (i & 0xFF ) + "." +                ((i >> 8 ) & 0xFF) + "." +                ((i >> 16 ) & 0xFF) + "." +                ( i >> 24 & 0xFF) ;    }    private void registerBroadcast() {        receiver = new MessageBroadcastReceiver();        IntentFilter filter = new IntentFilter("com.commonlibrary.mina.broadcast");        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }    @Override    protected void onDestroy() {        super.onDestroy();        stopService(new Intent(this, MinaService.class));        unregisterBroadcast();    }    private void unregisterBroadcast(){        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);    }    private class MessageBroadcastReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            mTextView.setText(intent.getStringExtra("message"));        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 后台和服务器通信的Service
package com.mina;import android.app.Service;import android.content.Context;import android.content.Intent;import android.os.HandlerThread;import android.os.IBinder;import android.support.annotation.Nullable;import android.util.Log;/** * Created by Coder on 2017/4/27. */public class MinaService extends Service{    private ConnectionThread thread;    @Override    public void onCreate() {        super.onCreate();        thread = new ConnectionThread("mina", getApplicationContext());        thread.start();        Log.i("tag", "启动线程尝试连接");    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        super.onDestroy();        thread.disConnect();        thread=null;    }    @Nullable    @Override    public IBinder onBind(Intent intent) {        return null;    }    class ConnectionThread extends HandlerThread{        private Context context;        boolean isConnection;        ConnectionManager mManager;        public ConnectionThread(String name, Context context){            super(name);            this.context = context;            //初始化连接配置信息            ConnectionConfig config = new ConnectionConfig.Builder(context)                    .setIp("10.101.252.112")                    .setPort(9555)                    .setReadBufferSize(10240)                    .setConnectionTimeOut(10000).builder();            //根据哦配置信息,生成连接管理类            mManager = new ConnectionManager(config);        }        @Override        protected void onLooperPrepared() {            while(true){                isConnection = mManager.connect();                if(isConnection){                    Log.i("tag", "连接成功");                    break;                }                try {                    Log.i("tag", "尝试重新连接");                    Thread.sleep(3000);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }        public void disConnect(){            mManager.disConnect();        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 网络连接的配置和参数类
package com.mina;import android.content.Context;/** * Created by Coder on 2017/4/27. */public class ConnectionConfig {    private Context context;    private String ip;    private int port;    private int readBufferSize;    private long connectionTimeOut;    public Context getContext() {        return context;    }    public String getIp() {        return ip;    }    public int getPort() {        return port;    }    public int getReadBufferSize() {        return readBufferSize;    }    public long getConnectionTimeOut() {        return connectionTimeOut;    }    public static class Builder{        private Context context;        private String ip = "192.168.0.100";        private int port = 9444;        private int readBufferSize = 10240;        private long connectionTimeOut = 10000;        public Builder(Context context){            this.context = context;        }        public Builder setIp(String ip){            this.ip = ip;            return this;        }        public Builder setPort(int port){            this.port = port;            return this;        }        public Builder setReadBufferSize(int readBufferSize){            this.readBufferSize = readBufferSize;            return this;        }        public Builder setConnectionTimeOut(long connectionTimeOut){            this.connectionTimeOut = connectionTimeOut;            return this;        }        private void applyConfig(ConnectionConfig config){            config.context = this.context;            config.ip = this.ip;            config.port = this.port;            config.readBufferSize = this.readBufferSize;            config.connectionTimeOut = this.connectionTimeOut;        }        public ConnectionConfig builder(){            ConnectionConfig config = new ConnectionConfig();            applyConfig(config);            return config;        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • TCP连接的管理类
package com.mina;import android.content.Context;import android.content.Intent;import android.support.v4.content.LocalBroadcastManager;import android.util.Log;import org.apache.mina.core.future.ConnectFuture;import org.apache.mina.core.service.IoHandlerAdapter;import org.apache.mina.core.session.IoSession;import org.apache.mina.filter.codec.ProtocolCodecFilter;import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;import org.apache.mina.filter.logging.LoggingFilter;import org.apache.mina.transport.socket.nio.NioSocketConnector;import java.lang.ref.WeakReference;import java.net.InetSocketAddress;/** * Created by Coder on 2017/4/27. */public class ConnectionManager {    private static final String BROADCAST_ACTION = "com.commonlibrary.mina.broadcast";    private static final String MESSAGE = "message";    private ConnectionConfig mConfig;    private WeakReference<Context> mContext;    private NioSocketConnector mConnection;    private IoSession mSession;    private InetSocketAddress mAddress;    public ConnectionManager(ConnectionConfig config){        this.mConfig = config;        this.mContext = new WeakReference<Context>(config.getContext());        init();    }    private void init() {        Log.i("ip:", mConfig.getIp());        Log.i("port:", ""+mConfig.getPort());        mAddress = new InetSocketAddress(mConfig.getIp(), mConfig.getPort());        mConnection = new NioSocketConnector();        mConnection.getSessionConfig().setReadBufferSize(mConfig.getReadBufferSize());        mConnection.getFilterChain().addLast("logging", new LoggingFilter());        mConnection.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));        mConnection.setHandler(new DefaultHandler(mContext.get()));        mConnection.setDefaultRemoteAddress(mAddress);    }    /**     * 与服务器连接     * @return     */    public boolean connect(){        Log.i("tag", "准备连接");        try{            ConnectFuture future = mConnection.connect();            future.awaitUninterruptibly();            mSession = future.getSession();            SessionManager.getInstance().setSeesion(mSession);        }catch (Exception e){            e.printStackTrace();            Log.i("tag", "连接失败");            return false;        }        return mSession == null ? false : true;    }    /**     * 断开连接     */    public void disConnect(){        mConnection.dispose();        mConnection=null;        mSession=null;        mAddress=null;        mContext = null;        Log.i("tag", "断开连接");    }    private static class DefaultHandler extends IoHandlerAdapter{        private Context mContext;        private DefaultHandler(Context context){            this.mContext = context;        }        @Override        public void sessionOpened(IoSession session) throws Exception {            super.sessionOpened(session);        }        @Override        public void messageReceived(IoSession session, Object message) throws Exception {            Log.i("tag", "接收到服务器端消息:"+message.toString());            if(mContext!=null){                Intent intent = new Intent(BROADCAST_ACTION);                intent.putExtra(MESSAGE, message.toString());                LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);            }        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • Session的管理类
package com.mina;import android.content.Context;import android.content.Intent;import android.support.v4.content.LocalBroadcastManager;import android.util.Log;import org.apache.mina.core.future.ConnectFuture;import org.apache.mina.core.service.IoHandlerAdapter;import org.apache.mina.core.session.IoSession;import org.apache.mina.filter.codec.ProtocolCodecFilter;import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;import org.apache.mina.filter.logging.LoggingFilter;import org.apache.mina.transport.socket.nio.NioSocketConnector;import java.lang.ref.WeakReference;import java.net.InetSocketAddress;/** * Created by Coder on 2017/4/27. */public class ConnectionManager {    private static final String BROADCAST_ACTION = "com.commonlibrary.mina.broadcast";    private static final String MESSAGE = "message";    private ConnectionConfig mConfig;    private WeakReference<Context> mContext;    private NioSocketConnector mConnection;    private IoSession mSession;    private InetSocketAddress mAddress;    public ConnectionManager(ConnectionConfig config){        this.mConfig = config;        this.mContext = new WeakReference<Context>(config.getContext());        init();    }    private void init() {        Log.i("ip:", mConfig.getIp());        Log.i("port:", ""+mConfig.getPort());        mAddress = new InetSocketAddress(mConfig.getIp(), mConfig.getPort());        mConnection = new NioSocketConnector();        mConnection.getSessionConfig().setReadBufferSize(mConfig.getReadBufferSize());        mConnection.getFilterChain().addLast("logging", new LoggingFilter());        mConnection.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));        mConnection.setHandler(new DefaultHandler(mContext.get()));        mConnection.setDefaultRemoteAddress(mAddress);    }    /**     * 与服务器连接     * @return     */    public boolean connect(){        Log.i("tag", "准备连接");        try{            ConnectFuture future = mConnection.connect();            future.awaitUninterruptibly();            mSession = future.getSession();            SessionManager.getInstance().setSeesion(mSession);        }catch (Exception e){            e.printStackTrace();            Log.i("tag", "连接失败");            return false;        }        return mSession == null ? false : true;    }    /**     * 断开连接     */    public void disConnect(){        mConnection.dispose();        mConnection=null;        mSession=null;        mAddress=null;        mContext = null;        Log.i("tag", "断开连接");    }    private static class DefaultHandler extends IoHandlerAdapter{        private Context mContext;        private DefaultHandler(Context context){            this.mContext = context;        }        @Override        public void sessionOpened(IoSession session) throws Exception {            super.sessionOpened(session);        }        @Override        public void messageReceived(IoSession session, Object message) throws Exception {            Log.i("tag", "接收到服务器端消息:"+message.toString());            if(mContext!=null){                Intent intent = new Intent(BROADCAST_ACTION);                intent.putExtra(MESSAGE, message.toString());                LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);            }        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111

效果

  • 服务器端
启动服务。。。。服务器与客户端创建连接...服务器与客户端连接打开...接收到的数据:10.115.38.46接收到的数据:Thu Apr 27 20:16:59 CST 2017
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 安卓端

这里写图片描述

I/tag: 启动线程尝试连接I/tag: 准备连接I/System.out: [CDS]connect[/10.101.252.112:9555]I/tag: 连接成功E/tag: 点击发送消息I/tag: 客户端准备发送消息I/System.out: [CDS]EAGAIN in RecvfromI/tag: 接收到服务器端消息:Thu Apr 27 20:20:58 CST 2017I/System.out: [CDS]close[35751]I/NetworkManagementSocketTagger: untagSocket(84)
原创粉丝点击