创建服务端程序
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId>
<version>2.0.16</version>
</dependency>
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 {
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 {
super.messageSent(session, message);
}
@Override
public void sessionClosed(IoSession session) throws Exception {
super.sessionClosed(session);
}
}
}
安卓端代码
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());
}
});
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
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) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
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"));
}
}
}
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();
}
}
}
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;
}
}
}
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);
}
}
}
}
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);
}
}
}
}
效果
启动服务。。。。
服务器与客户端创建连接...
服务器与客户端连接打开...
接收到的数据:10.115.38.46
接收到的数据:Thu Apr 27 20:16:59 CST 2017
![这里写图片描述](https://img-blog.csdn.net/20170427202218294?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYU5vb2JDb2Rlcg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
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 Recvfrom
I/tag: 接收到服务器端消息:Thu Apr 27 20:20:58 CST 2017
I/System.out: [CDS]close[35751]
I/NetworkManagementSocketTagger: untagSocket(84)