Socket for android 簡單實例

Socket for android 簡單實例

最近在實現(xiàn)socket通信,所以寫個demo來簡單實現(xiàn)下。我用了一種是原始的socket實現(xiàn),另一種是MINA框架來實現(xiàn)的。

下載demo:http://download.csdn.net/detail/qq_29774291/9826648

一.先看第一種方法

a)、創(chuàng)建Socket對象,指明需要連接的服務器的地址和端口。

b)、建立連接后,通過輸出流向服務器發(fā)送請求信息。

c)、通過輸入流獲取服務器的響應信息。

d)、關閉響應資源

如下是主要代碼

package com.item.item.sock.socket;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.SystemClock;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.InetSocketAddress;import java.net.Socket;import java.net.SocketAddress;/**

* Socket 通信 */public class MyServiceOne extends Service { ? ?private Socket socket; ? ?private BufferedReader in = null; ? ?private BufferedWriter out = null; ? ?private boolean close = true; ? ?private Thread readThread;

@Override ? ?public IBinder onBind(Intent intent) { ? ? ? ?// TODO: Return the communication channel to the service.

throw new UnsupportedOperationException("Not yet implemented");

}

@Override ? ?public void onCreate() { ? ? ? ?super.onCreate();

close = true; ? ? ? ?new Thread(new Runnable() {

@Override ? ? ? ? ? ?public void run() { ? ? ? ? ? ? ? ?int count = 0; ? ? ? ? ? ? ? ?for(;;){ ? ? ? ? ? ? ? ? ? ?try {

count++;

SocketAddress socketAddress = new InetSocketAddress(ConnectUtils.HOST,ConnectUtils.POST);

socket = new Socket();

socket.connect(socketAddress,10000); ? ? ? ? ? ? ? ? ? ? ? ?if(socket.isConnected()){

System.out.println("socket 連接成功");

in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));

out =new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8")); ? ? ? ? ? ? ? ? ? ? ? ? ? ?//發(fā)送一個消息

out.write("start");

out.flush(); ? ? ? ? ? ? ? ? ? ? ? ? ? ?//開啟一個線程來讀取服務器發(fā)來的消息 ? ? ? ? ? ? ? ? ? ? ? ? ? ?readThread.start(); ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;

}

}catch (Exception e){ ? ? ? ? ? ? ? ? ? ? ? ?if(count > ConnectUtils.IDLE_TIME){ ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;

}else {

SystemClock.sleep(5000);

}

}

}

}

}).start();

readThread = new Thread(new Runnable() {

@Override ? ? ? ? ? ?public void run() { ? ? ? ? ? ? ? ?while (close){

String readtext = readText(socket); ? ? ? ? ? ? ? ? ? ?if(readtext !=null){

System.out.println("服務器發(fā)來的消息:" + readtext);

}

}

}

});

} ? ?private String readText(Socket socket) {

String string = null; ? ? ? ?if(socket.isConnected()){ ? ? ? ? ? ?try { ? ? ? ? ? ? ? ?char[] buffer = new char[8000]; ? ? ? ? ? ? ? ?int count = 0; ? ? ? ? ? ? ? ?if((count = in.read(buffer)) > 0){ ? ? ? ? ? ? ? ? ? ?char[] temp = new char[count]; ? ? ? ? ? ? ? ? ? ?for(int i=0;i

temp[i] = buffer[i];

}

string = new String(temp);

}

}catch (Exception e){

string = null;

}

} ? ? ? ?return ?string;

}

@Override ? ?public void onDestroy() { ? ? ? ?super.onDestroy();

close = false; ? ? ? ?if(socket != null){ ? ? ? ? ? ?try {

socket.close();

socket = null;

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

二.第二種方法是用MINA框架實現(xiàn)的

package com.item.item.sock.socket;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.SystemClock;import android.util.Log;import org.apache.mina.core.future.ConnectFuture;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.ProtocolCodecFilter;import org.apache.mina.filter.codec.textline.TextLineCodecFactory;import org.apache.mina.transport.socket.nio.NioSocketConnector;import java.net.InetSocketAddress;import java.nio.charset.Charset;/**

* 使用MINA框架實現(xiàn)socket通信

* 由于接受消息會阻塞Android線程,所以開在子線程中(同時將其放在Service中,讓其在后臺運行) */public class MyServiceTwo extends Service { ? ?private String TAG = "jiejie"; ? ?private IoSession session = null; ? ?private MinaClientHandler minaClientHandler; ? ?private NioSocketConnector connector = null;

@Override ? ?public IBinder onBind(Intent intent) { ? ? ? ?// TODO: Return the communication channel to the service.

throw new UnsupportedOperationException("Not yet implemented");

}

@Override ? ?public void onCreate() { ? ? ? ?super.onCreate();

minaClientHandler = new MinaClientHandler(); ? ? ? ?new Thread(new Runnable() {

@Override ? ? ? ? ? ?public void run() { ? ? ? ? ? ? ? ?//創(chuàng)建連接客戶端

connector = new NioSocketConnector(); ? ? ? ? ? ? ? ?//設置連接超時時間

connector.setConnectTimeoutMillis(30000); ? ? ? ? ? ? ? ?//添加過濾器

connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); ? ? ? ? ? ? ? ?//設置接收緩沖區(qū)大小

connector.getSessionConfig().setReadBufferSize(1024); ? ? ? ? ? ? ? ?//設置處理器 ? ? ? ? ? ? ? ?connector.setHandler(minaClientHandler); ? ? ? ? ? ? ? ?//設置默認方位地址

connector.setDefaultRemoteAddress(new InetSocketAddress(ConnectUtils.HOST,ConnectUtils.POST)); ? ? ? ? ? ? ? ?//添加重連監(jiān)聽

connector.addListener(new IoListener(){

@Override ? ? ? ? ? ? ? ? ? ?public void sessionDestroyed(IoSession ioSession) throws Exception { ? ? ? ? ? ? ? ? ? ? ? ?int count = 0; ? ? ? ? ? ? ? ? ? ? ? ?for(;;){ ? ? ? ? ? ? ? ? ? ? ? ? ? ?try {

count++;

ConnectFuture future = connector.connect();

future.awaitUninterruptibly();//等待連接創(chuàng)建完成

session = future.getSession();//獲取session

if(session.isConnected()){

System.out.println("斷線了 但是又重連了");

count = 0; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;

}

}catch (Exception e){ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?if(count > ConnectUtils.IDLE_TIME){ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;

}else {

SystemClock.sleep(5000);

}

}

}

}

}); ? ? ? ? ? ? ? ?for(;;){ ? ? ? ? ? ? ? ? ? ?try {

ConnectFuture future = connector.connect();

future.awaitUninterruptibly();

System.out.println("socket 連接成功");

session = future.getSession();

session.write("start"); ? ? ? ? ? ? ? ? ? ? ? ?break;

}catch (Exception e){

SystemClock.sleep(5000);

}

}

}

}).start();

}

@Override ? ?public void onDestroy() { ? ? ? ?super.onDestroy();

connector.dispose();

} ? ?private class MinaClientHandler extends IoHandlerAdapter{

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

Log.d(TAG,"exceptionCaught--------" + cause);

}

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

Log.d(TAG,"messageReceived---------"? + message ? ?);

}

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

Log.d(TAG,"messageSent-------" + message);

}

@Override ? ? ? ?public void sessionClosed(IoSession session) throws Exception { ? ? ? ? ? ?super.sessionClosed(session);

Log.d(TAG,"sessionClosed-------");

}

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

Log.d(TAG,"sessionCreated------" + session);

}

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

Log.d(TAG,"sessionOpened---------");

}

} ? ?/**

* 創(chuàng)建一個監(jiān)聽器實現(xiàn)mina的IoServiceListener接口,里面的方法可以不用實現(xiàn) ? ? */

private class IoListener implements IoServiceListener{

@Override ? ? ? ?public void serviceActivated(IoService ioService) throws Exception {

}

@Override ? ? ? ?public void serviceIdle(IoService ioService, IdleStatus idleStatus) throws Exception {

}

@Override ? ? ? ?public void serviceDeactivated(IoService ioService) throws Exception {

}

@Override ? ? ? ?public void sessionCreated(IoSession ioSession) throws Exception {

}

@Override ? ? ? ?public void sessionClosed(IoSession ioSession) throws Exception {

}

@Override ? ? ? ?public void sessionDestroyed(IoSession ioSession) throws Exception {

}

}

}

三.對于粘包的處理? 是建立臨時緩沖區(qū)來處理

public synchronized void Decode(char[] data)

{ ? ? ? ?for (int i = 0; i < data.length; i++)

{ ? ? ? ? ? ?char byt = data[i]; ? ? ? ? ? ?this.temp.add(byt); ? ? ? ? ? ?if (byt == '"')

{ ? ? ? ? ? ? ? ?if (!this.instring)

{ ? ? ? ? ? ? ? ? ? ?this.instring = true;

} ? ? ? ? ? ? ? ?else if (getPrev() != '\\')

{ ? ? ? ? ? ? ? ? ? ?this.instring = false;

}

} ? ? ? ? ? ?if (instring) continue; ? ? ? ? ? ?if (byt == '}' || byt == ']')

{

end = true;

left--;

} ? ? ? ? ? ?if (byt == '{' || byt == '[')

{

left++;

} ? ? ? ? ? ?if ((left) < 0)

{

temp.clear(); ? ? ? ? ? ? ? ?this.instring = false; ? ? ? ? ? ? ? ?this.left = 0; ? ? ? ? ? ? ? ?continue;

} ? ? ? ? ? ?if (end && left == 0)

{

end = false; ? ? ? ? ? ? ? ?char[] p =new char[temp.size()]; ? ? ? ? ? ? ? ?// temp.toArray(p) ;//完整協(xié)議包

for(int j =0; j< temp.size();j++){

p[j] = temp.get(j);

}

// todo : log// ? ? ? ? ? ? ? ?if (OnPackageHanded != null) {// ? ? ? ? ? ? ? ? ? ?OnPackageHanded(package);// ? ? ? ? ? ? ? ?}

if(this.HandledPackage.size()>100){

this.HandledPackage.poll();

} ? ? ? ? ? ? ? ?this.HandledPackage.offer(p);

temp.clear(); ? ? ? ? ? ? ? ?this.instring = false; ? ? ? ? ? ? ? ?this.left = 0; ? ? ? ? ? ? ? ?continue;

}

}

}

歡迎加入技術交流群:364595326

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評論 19 139
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,835評論 18 399
  • 小編費力收集:給你想要的面試集合 1.C++或Java中的異常處理機制的簡單原理和應用。 當JAVA程序違反了JA...
    八爺君閱讀 5,239評論 1 114
  • 1、不安全的隨機數(shù)生成,在CSRF TOKEN生成、password reset token生成等,會造成toke...
    nightmare丿閱讀 4,000評論 0 1
  • 1. 前幾天,我在大學同學Maggie的朋友圈看到這樣一大段話: 每次孩子在學校受了委屈、發(fā)生矛盾、甚至被人欺負了...
    萬伊刀閱讀 5,192評論 69 88

友情鏈接更多精彩內容