Android編程實(shí)現(xiàn)TCP客戶端的方法
本文實(shí)例講述了Android編程實(shí)現(xiàn)TCP客戶端的方法。分享給大家供大家參考,具體如下:
因?yàn)轫?xiàng)目上需要實(shí)現(xiàn)一個(gè)TCP Client 端;在網(wǎng)上找好多例子基本上都是阻塞方式完成;
我的實(shí)現(xiàn)例子:由Activity 及sever 來實(shí)現(xiàn),在sever 創(chuàng)建一個(gè)線程來監(jiān)聽接受數(shù)據(jù)。收到數(shù)據(jù),通過廣播發(fā)送給Activity;
服務(wù)端我沒有去實(shí)現(xiàn),你可以下載TCP Socket 調(diào)試工具v2.2;創(chuàng)建個(gè)9005端口;客戶端:訪問的IP為10.0.2.2

AnetTest.java:
/**
* Copyright 2010 archfree
*
*/
package com.archfree.demo;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AnetTest extends Activity {
/**
* 通過ServiceConnection的內(nèi)部類實(shí)現(xiàn)來連接Service和Activity
*
*/
public static final String TAG = "AnetTest";
private static final boolean DEBUG = true;// false
private String msg = "";
private UpdateReceiver mReceiver;
private Context mContext;
private ReceiveMessage mReceiveMessage;
// 實(shí)現(xiàn)一個(gè) BroadcastReceiver,用于接收指定的 Broadcast
public class UpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG)
Log.d(TAG, "onReceive: " + intent);
msg = intent.getStringExtra("msg");
System.out.println("recv:" + msg);
// System.out.println();
((EditText) findViewById(R.id.tv_recv)).append(msg + "/n");
}
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mReceiveMessage = ((ReceiveMessage.LocalBinder) service)
.getService();
if (DEBUG)
Log.d(TAG, "on serivce connected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
mReceiveMessage = null;
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 實(shí)例化自定義的 BroadcastReceiver
mReceiver = new UpdateReceiver();
IntentFilter filter = new IntentFilter();
// 為 BroadcastReceiver 指定 action ,使之用于接收同 action 的廣播
filter.addAction("com.archfree.demo.msg");
// 以編程方式注冊(cè) BroadcastReceiver 。配置方式注冊(cè) BroadcastReceiver 的例子見
// AndroidManifest.xml 文件
// 一般在 OnStart 時(shí)注冊(cè),在 OnStop 時(shí)取消注冊(cè)
this.registerReceiver(mReceiver, filter);
mContext = AnetTest.this;
/**
* Button bn_conn bn_send bn_bind bn_unbind
*/
// Button bn_conn = (Button) findViewById(R.id.bn_conn);
Button bn_send = (Button) findViewById(R.id.bn_send);
Button bn_bind = (Button) findViewById(R.id.bn_bind);
Button bn_unbind = (Button) findViewById(R.id.bn_unbind);
EditText tv_recv = (EditText) findViewById(R.id.tv_recv);
/**
* EditText et_send
*/
EditText et_send = (EditText) findViewById(R.id.et_send);
/**
* bn_send on click
*/
bn_send.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO
((EditText) findViewById(R.id.tv_recv)).clearComposingText();
mReceiveMessage
.SendMessageToServer("0001058512250000190010900005300010001354758032278512 460029807503542 0613408000011 ");
}
});
/**
* bn_bind on click
*/
bn_bind.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO
Intent i = new Intent();
Bundle bundle = new Bundle();
bundle.putString("chatmessage",
((EditText) findViewById(R.id.et_send)).getText()
.toString());
i.putExtras(bundle);
System.out.println(" send onclick");
bindService(new Intent("com.archfree.demo.ReceiveMessage"),
serviceConnection, BIND_AUTO_CREATE);
}
});
/**
* bn_unbind on click
*/
bn_unbind.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO
mContext.unbindService(serviceConnection);
}
});
/**
* Activity和本地服務(wù)交互,需要使用bind和unbind方法
* */
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unbindService(serviceConnection);
unregisterReceiver(mReceiver);
}
}
ReceiveMessage.java 參考網(wǎng)絡(luò)資源,修改;
package com.archfree.demo;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class ReceiveMessage extends Service {
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// // TODO Auto-generated method stub
// return super.onStartCommand(intent, flags, startId);
// }
private SocketChannel client = null;
private InetSocketAddress isa = null;
private String message = "";
public void onCreate() {
System.out.println("----- onCreate---------");
super.onCreate();
ConnectToServer();
StartServerListener();
}
public void onDestroy() {
super.onDestroy();
DisConnectToServer();
}
public void onStart(Intent intent, int startId) {
System.out.println("----- onStart---------");
super.onStart(intent, startId);
}
/*
* IBinder方法 , LocalBinder 類,mBinder接口這三項(xiàng)用于
* Activity進(jìn)行Service的綁定,點(diǎn)擊發(fā)送消息按鈕之后觸發(fā)綁定 并通過Intent將Activity中的EditText的值
* 傳送到Service中向服務(wù)器發(fā)送
*/
public IBinder onBind(Intent intent) {
System.out.println("----- onBind---------");
// message = intent.getStringExtra("chatmessage");
// if (message.length() > 0) {
// SendMessageToServer(message);
// }
return mBinder;
}
public class LocalBinder extends Binder {
ReceiveMessage getService() {
return ReceiveMessage.this;
}
}
private final IBinder mBinder = new LocalBinder();
// 用于鏈接服務(wù)器端
public void ConnectToServer() {
try {
client = SocketChannel.open();
//isa = new InetSocketAddress("10.0.2.2", 9005);
isa = new InetSocketAddress("211.141.230.246", 6666);
client.connect(isa);
client.configureBlocking(false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 斷開與服務(wù)器端的鏈接
public void DisConnectToServer() {
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 啟動(dòng)服務(wù)器端的監(jiān)聽線程,從Server端接收消息
public void StartServerListener() {
ServerListener a = new ServerListener();
a.start();
}
// 向Server端發(fā)送消息
public void SendMessageToServer(String msg) {
System.out.println("Send:" + msg);
try {
ByteBuffer bytebuf = ByteBuffer.allocate(1024);
bytebuf = ByteBuffer.wrap(msg.getBytes("UTF-8"));
client.write(bytebuf);
bytebuf.flip();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(" SendMessageToServer IOException===");
}
}
private void shownotification(String tab) {
System.out.println("shownotification=====" + tab);
NotificationManager barmanager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification msg = new Notification(
android.R.drawable.stat_notify_chat, "A Message Coming!",
System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AnetTest.class), PendingIntent.FLAG_ONE_SHOT);
msg.setLatestEventInfo(this, "Message", "Message:" + tab, contentIntent);
barmanager.notify(0, msg);
}
// 發(fā)送廣播信息
private void sendMsg(String msg){
// 指定廣播目標(biāo)的 action (注:指定了此 action 的 receiver 會(huì)接收此廣播)
Intent intent = new Intent("com.archfree.demo.msg");
// 需要傳遞的參數(shù)
intent.putExtra("msg", msg);
// 發(fā)送廣播
this.sendBroadcast(intent);
}
private class ServerListener extends Thread {
//private ByteBuffer buf = ByteBuffer.allocate(1024);
public void run() {
try {
// 無線循環(huán),監(jiān)聽服務(wù)器,如果有不為空的信息送達(dá),則更新Activity的UI
while (true) {
ByteBuffer buf = ByteBuffer.allocate(1024);
//buf.clear();
client.read(buf);
buf.flip();
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer;
charBuffer = decoder.decode(buf);
String result = charBuffer.toString();
if (result.length() > 0)
{// recvData(result);
sendMsg(result);
//System.out.println("+++++="+result);
//shownotification(result);
}
// System.out.println("++++++++++++++++++="+result);
}
} catch (CharacterCodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.archfree.demo" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AnetTest" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android通信方式總結(jié)》、《Android調(diào)試技巧與常見問題解決方法匯總》、《Android開發(fā)入門與進(jìn)階教程》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
相關(guān)文章
Android Rreact Native 常見錯(cuò)誤總結(jié)
這篇文章主要介紹了Android Rreact Native 常見錯(cuò)誤總結(jié)的相關(guān)資料,需要的朋友可以參考下2017-06-06
Android SQLite數(shù)據(jù)庫進(jìn)行查詢優(yōu)化的方法
這篇文章主要給大家介紹了關(guān)于Android SQLite數(shù)據(jù)庫進(jìn)行查詢優(yōu)化的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11
揭秘雙十一手機(jī)淘寶圖標(biāo)如何被動(dòng)態(tài)更換
這篇文章主要介紹了每到雙十一十二的時(shí)候Android手機(jī)動(dòng)態(tài)更換手機(jī)圖標(biāo)的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08
Android自定義View新年煙花、祝福語橫幅動(dòng)畫
這篇文章主要為大家詳細(xì)介紹了Android自定義View新年煙花、祝福語橫幅動(dòng)畫,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
Android編程之客戶端通過socket與服務(wù)器通信的方法
這篇文章主要介紹了Android編程之客戶端通過socket與服務(wù)器通信的方法,結(jié)合實(shí)例形式分析了Android基于socket通訊的具體步驟與相關(guān)使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
Android實(shí)現(xiàn)多線程下載圖片的方法
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)多線程下載圖片的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09
Android?Flutter實(shí)現(xiàn)搜索的三種方式詳解
這篇文章主要為大家詳細(xì)介紹了Android?Flutter實(shí)現(xiàn)搜索的三種方式,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的可以了解一下2022-08-08
Android的Glide庫加載圖片的用法及其與Picasso的對(duì)比
這篇文章主要介紹了Android的Glide庫加載圖片的用法及其與Picasso的對(duì)比,Glide的加載gif圖片的功能和性能受到了很多開發(fā)者的青睞,需要的朋友可以參考下2016-04-04
如何設(shè)置Android studio 3.0顯示光標(biāo)返回上一次瀏覽位置的箭頭圖標(biāo)
這篇文章主要介紹了如何設(shè)置Android studio 3.0顯示光標(biāo)返回上一次瀏覽位置的箭頭圖標(biāo) 很多朋友反映剛升級(jí)了Android studio 3.0,發(fā)現(xiàn)光標(biāo)返回上一次瀏覽位置的箭頭圖標(biāo)沒有了,下文給大家介紹的非常詳細(xì),需要的朋友可以參考下2017-11-11

