Mina框架---Android与服务器通信

568 查看

Mina是Apache的一個基於NioSocket的框架

环境搭配

下载地址:Mina , slf4j(Android)

服务器程序中

载入libs:
mina-core-2.0.9.jar
slf4j-api-1.7.7.jar

客户端程序中

载入libs:
android-support-v4.jar
mina-core-2.0.7.jar
slf4j-android-1.6.1-RC1.jar

代码

服务器程序

MinaServer.java

public class MinaServer {
    public static void main(String[]args){
        try{
            NioSocketAcceptor acceptor = new NioSocketAcceptor();
            acceptor.setHandler(new ServerHandler());   //处理
            acceptor.getFilterChain().addLast("codec", new     ProtocolCodecFilter(new TextLineCodecFactory()));//过滤消息
            acceptor.bind(new InetSocketAddress(9900)); //指定port
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

ServerHandler.java (处理器)

public class ServerHandler extends IoHandlerAdapter {

    MySQL mysql;

    //异常
    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {

    }

    //接收信息
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        String msg = (String)message;
        System.out.println(msg);
    }

    //发送信息
    @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);
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        super.sessionCreated(session);
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        super.sessionIdle(session, status);
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
    }
}

客户端程序

MyActivity.java

@SuppressWarnings("ALL")
public class MyActivity extends Activity {

Button btn_send;
TextView tv_msg;
EditText etv_type_msg;

private String IP = "192.168.2.174";
private int PORT = 9900;
String msg_send = "";

SocketConnector connector;
SocketAddress socketAddress;
ConnectFuture future;
IoFilter filter;

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  System.setProperty("java.net.preferIPv6Addresses","false");

  btn_send = (Button)findViewById(R.id.btn_send);
  tv_msg = (TextView)findViewById(R.id.tv_msg);
  etv_type_msg = (EditText)findViewById(R.id.etv_type_msg);
  tv_msg.setEllipsize(TextUtils.TruncateAt.MARQUEE);
  tv_msg.setMarqueeRepeatLimit(6);
  connector = new NioSocketConnector();
  filter = new ProtocolCodecFilter(new TextLineCodecFactory());
  connector.getFilterChain().addLast("codec", filter);
  socketAddress = new InetSocketAddress(IP,PORT);
  connector.setHandler(new ClientHandler());
  future = connector.connect(socketAddress);

  future.join();
  if (!future.isConnected()) {
   tv_msg.setText("Connect fail");
   future.getException().printStackTrace();
   return;
  } else {
   final IoSession session = future.getSession();
   etv_type_msg.setText("");
   session.write("Connect Successful");
   btn_send.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     String sendMsgText = etv_type_msg.getText().toString() + "\r\n";
     session.write(sendMsgText);
     tv_msg.append(sendMsgText);
     etv_type_msg.setText("");
    }
   });
  }
 }
}

ClientHandler.java

package com.blogspot.cartonsbase.Client;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

public class ClientHandler extends IoHandlerAdapter{

    public void messageReceived(IoSession session, Object message) throws Exception {
        super.messageReceived(session, message);
    }

    public void exceptionCaught(IoSession session, Throwable cause)throws Exception {
        super.exceptionCaught(session, cause);
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        super.messageSent(session, message);
    }

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.blogspot.cartonsbase.Client"
          android:versionCode="1"
          android:versionName="1.0"
  >

 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" >
 </uses-permission>
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" >
 </uses-permission>
 <uses-permission android:name="android.permission.INTERNET" >
 </uses-permission>
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
 </uses-permission>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
 </uses-permission>
 <uses-permission android:name="android.permission.READ_PHONE_STATE" >
 </uses-permission>
 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
 </uses-permission>
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
 </uses-permission>
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
 </uses-permission>
 <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
 <uses-permission android:name="android.permission.RECEIVE_SMS" />
 <uses-permission android:name="android.permission.SEND_SMS" />
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
 <uses-permission android:name="android.permission.CALL_PHONE" >
 </uses-permission>
 <application
   android:label="@string/app_name"
   android:icon="@drawable/ic_launcher"
   >
  <activity
    android:name="MyActivity"
    android:label="@string/app_name"
    >
   <intent-filter>
    <action android:name="android.intent.action.MAIN"/>
    <category android:name="android.intent.category.LAUNCHER"/>
   </intent-filter>
  </activity>
 </application>
</manifest>

code

所有文章与 http://cartonsbase.blogspot.com 同步