Android TCP 客户端实现
来源:互联网 发布:php const存储 编辑:程序博客网 时间:2024/05/16 18:45
因为项目上需要实现一个TCP Client 端;在网上找好多例子基本上都是阻塞方式完成;
我的实现例子:由Activity 及sever 来实现,在sever 创建一个线程来监听接受数据。收到数据,通过广播发送给Activity;
服务端我没有去实现,你可以下载TCP Socket 调试工具v2.2;创建个9005端口;客户端:访问的IP为10.0.2.2
AnetTest.java
1 /**
2 * Copyright 2010 archfree
3 *
4 */
5 package com.archfree.demo;
6
7 import android.app.Activity;
8 import android.content.BroadcastReceiver;
9 import android.content.ComponentName;
10 import android.content.Context;
11 import android.content.Intent;
12 import android.content.IntentFilter;
13 import android.content.ServiceConnection;
14
15 import android.os.Bundle;
16 import android.os.IBinder;
17 import android.util.Log;
18 import android.view.View;
19 import android.view.View.OnClickListener;
20 import android.widget.Button;
21 import android.widget.EditText;
22 import android.widget.TextView;
23
24 public class AnetTest extends Activity {
25
26 /**
27 * 通过ServiceConnection的内部类实现来连接Service和Activity
28 *
29 */
30 public static final String TAG = "AnetTest";
31 private static final boolean DEBUG = true;// false
32 private String msg = "";
33 private UpdateReceiver mReceiver;
34 private Context mContext;
35 private ReceiveMessage mReceiveMessage;
36
37 // 实现一个 BroadcastReceiver,用于接收指定的 Broadcast
38 public class UpdateReceiver extends BroadcastReceiver {
39
40 @Override
41 public void onReceive(Context context, Intent intent) {
42 if (DEBUG)
43 Log.d(TAG, "onReceive: " + intent);
44 msg = intent.getStringExtra("msg");
45 System.out.println("recv:" + msg);
46 // System.out.println();
47 ((EditText) findViewById(R.id.tv_recv)).append(msg + "/n");
48
49 }
50
51 }
52
53 private ServiceConnection serviceConnection = new ServiceConnection() {
54
55 @Override
56 public void onServiceConnected(ComponentName name, IBinder service) {
57
58 mReceiveMessage = ((ReceiveMessage.LocalBinder) service)
59 .getService();
60 if (DEBUG)
61 Log.d(TAG, "on serivce connected");
62
63 }
64
65 @Override
66 public void onServiceDisconnected(ComponentName name) {
67 mReceiveMessage = null;
68 }
69 };
70
71 /** Called when the activity is first created. */
72 @Override
73 public void onCreate(Bundle savedInstanceState) {
74 super.onCreate(savedInstanceState);
75 setContentView(R.layout.main);
76
77 // 实例化自定义的 BroadcastReceiver
78 mReceiver = new UpdateReceiver();
79 IntentFilter filter = new IntentFilter();
80 // 为 BroadcastReceiver 指定 action ,使之用于接收同 action 的广播
81 filter.addAction("com.archfree.demo.msg");
82
83 // 以编程方式注册 BroadcastReceiver 。配置方式注册 BroadcastReceiver 的例子见
84 // AndroidManifest.xml 文件
85 // 一般在 OnStart 时注册,在 OnStop 时取消注册
86 this.registerReceiver(mReceiver, filter);
87
88 mContext = AnetTest.this;
89 /**
90 * Button bn_conn bn_send bn_bind bn_unbind
91 */
92
93 // Button bn_conn = (Button) findViewById(R.id.bn_conn);
94 Button bn_send = (Button) findViewById(R.id.bn_send);
95 Button bn_bind = (Button) findViewById(R.id.bn_bind);
96 Button bn_unbind = (Button) findViewById(R.id.bn_unbind);
97 EditText tv_recv = (EditText) findViewById(R.id.tv_recv);
98 /**
99 * EditText et_send
100 */
101
102 EditText et_send = (EditText) findViewById(R.id.et_send);
103
104 /**
105 * bn_send on click
106 */
107
108 bn_send.setOnClickListener(new OnClickListener() {
109
110 public void onClick(View arg0) {
111 // TODO
112 ((EditText) findViewById(R.id.tv_recv)).clearComposingText();
113
114 mReceiveMessage
115 .SendMessageToServer("0001058512250000190010900005300010001354758032278512 460029807503542 0613408000011 ");
116 }
117 });
118
119 /**
120 * bn_bind on click
121 */
122 bn_bind.setOnClickListener(new OnClickListener() {
123
124 public void onClick(View arg0) {
125 // TODO
126 Intent i = new Intent();
127 Bundle bundle = new Bundle();
128 bundle.putString("chatmessage",
129 ((EditText) findViewById(R.id.et_send)).getText()
130 .toString());
131 i.putExtras(bundle);
132 System.out.println(" send onclick");
133 bindService(new Intent("com.archfree.demo.ReceiveMessage"),
134 serviceConnection, BIND_AUTO_CREATE);
135
136 }
137 });
138 /**
139 * bn_unbind on click
140 */
141 bn_unbind.setOnClickListener(new OnClickListener() {
142
143 public void onClick(View arg0) {
144 // TODO
145 mContext.unbindService(serviceConnection);
146
147 }
148 });
149 /**
150 * Activity和本地服务交互,需要使用bind和unbind方法
151 * */
152
153 }
154
155 @Override
156 protected void onDestroy() {
157 // TODO Auto-generated method stub
158 super.onDestroy();
159 unbindService(serviceConnection);
160 unregisterReceiver(mReceiver);
161 }
162
163 }
2 * Copyright 2010 archfree
3 *
4 */
5 package com.archfree.demo;
6
7 import android.app.Activity;
8 import android.content.BroadcastReceiver;
9 import android.content.ComponentName;
10 import android.content.Context;
11 import android.content.Intent;
12 import android.content.IntentFilter;
13 import android.content.ServiceConnection;
14
15 import android.os.Bundle;
16 import android.os.IBinder;
17 import android.util.Log;
18 import android.view.View;
19 import android.view.View.OnClickListener;
20 import android.widget.Button;
21 import android.widget.EditText;
22 import android.widget.TextView;
23
24 public class AnetTest extends Activity {
25
26 /**
27 * 通过ServiceConnection的内部类实现来连接Service和Activity
28 *
29 */
30 public static final String TAG = "AnetTest";
31 private static final boolean DEBUG = true;// false
32 private String msg = "";
33 private UpdateReceiver mReceiver;
34 private Context mContext;
35 private ReceiveMessage mReceiveMessage;
36
37 // 实现一个 BroadcastReceiver,用于接收指定的 Broadcast
38 public class UpdateReceiver extends BroadcastReceiver {
39
40 @Override
41 public void onReceive(Context context, Intent intent) {
42 if (DEBUG)
43 Log.d(TAG, "onReceive: " + intent);
44 msg = intent.getStringExtra("msg");
45 System.out.println("recv:" + msg);
46 // System.out.println();
47 ((EditText) findViewById(R.id.tv_recv)).append(msg + "/n");
48
49 }
50
51 }
52
53 private ServiceConnection serviceConnection = new ServiceConnection() {
54
55 @Override
56 public void onServiceConnected(ComponentName name, IBinder service) {
57
58 mReceiveMessage = ((ReceiveMessage.LocalBinder) service)
59 .getService();
60 if (DEBUG)
61 Log.d(TAG, "on serivce connected");
62
63 }
64
65 @Override
66 public void onServiceDisconnected(ComponentName name) {
67 mReceiveMessage = null;
68 }
69 };
70
71 /** Called when the activity is first created. */
72 @Override
73 public void onCreate(Bundle savedInstanceState) {
74 super.onCreate(savedInstanceState);
75 setContentView(R.layout.main);
76
77 // 实例化自定义的 BroadcastReceiver
78 mReceiver = new UpdateReceiver();
79 IntentFilter filter = new IntentFilter();
80 // 为 BroadcastReceiver 指定 action ,使之用于接收同 action 的广播
81 filter.addAction("com.archfree.demo.msg");
82
83 // 以编程方式注册 BroadcastReceiver 。配置方式注册 BroadcastReceiver 的例子见
84 // AndroidManifest.xml 文件
85 // 一般在 OnStart 时注册,在 OnStop 时取消注册
86 this.registerReceiver(mReceiver, filter);
87
88 mContext = AnetTest.this;
89 /**
90 * Button bn_conn bn_send bn_bind bn_unbind
91 */
92
93 // Button bn_conn = (Button) findViewById(R.id.bn_conn);
94 Button bn_send = (Button) findViewById(R.id.bn_send);
95 Button bn_bind = (Button) findViewById(R.id.bn_bind);
96 Button bn_unbind = (Button) findViewById(R.id.bn_unbind);
97 EditText tv_recv = (EditText) findViewById(R.id.tv_recv);
98 /**
99 * EditText et_send
100 */
101
102 EditText et_send = (EditText) findViewById(R.id.et_send);
103
104 /**
105 * bn_send on click
106 */
107
108 bn_send.setOnClickListener(new OnClickListener() {
109
110 public void onClick(View arg0) {
111 // TODO
112 ((EditText) findViewById(R.id.tv_recv)).clearComposingText();
113
114 mReceiveMessage
115 .SendMessageToServer("0001058512250000190010900005300010001354758032278512 460029807503542 0613408000011 ");
116 }
117 });
118
119 /**
120 * bn_bind on click
121 */
122 bn_bind.setOnClickListener(new OnClickListener() {
123
124 public void onClick(View arg0) {
125 // TODO
126 Intent i = new Intent();
127 Bundle bundle = new Bundle();
128 bundle.putString("chatmessage",
129 ((EditText) findViewById(R.id.et_send)).getText()
130 .toString());
131 i.putExtras(bundle);
132 System.out.println(" send onclick");
133 bindService(new Intent("com.archfree.demo.ReceiveMessage"),
134 serviceConnection, BIND_AUTO_CREATE);
135
136 }
137 });
138 /**
139 * bn_unbind on click
140 */
141 bn_unbind.setOnClickListener(new OnClickListener() {
142
143 public void onClick(View arg0) {
144 // TODO
145 mContext.unbindService(serviceConnection);
146
147 }
148 });
149 /**
150 * Activity和本地服务交互,需要使用bind和unbind方法
151 * */
152
153 }
154
155 @Override
156 protected void onDestroy() {
157 // TODO Auto-generated method stub
158 super.onDestroy();
159 unbindService(serviceConnection);
160 unregisterReceiver(mReceiver);
161 }
162
163 }
=============================================================================================
ReceiveMessage.java 参考网络资源,修改;
1 package com.archfree.demo;
2
3 import java.io.IOException;
4 import java.net.InetSocketAddress;
5 import java.nio.ByteBuffer;
6 import java.nio.CharBuffer;
7 import java.nio.channels.SocketChannel;
8 import java.nio.charset.CharacterCodingException;
9 import java.nio.charset.Charset;
10 import java.nio.charset.CharsetDecoder;
11 import android.app.Notification;
12 import android.app.NotificationManager;
13 import android.app.PendingIntent;
14 import android.app.Service;
15 import android.content.Context;
16 import android.content.Intent;
17 import android.os.Binder;
18 import android.os.IBinder;
19
20 public class ReceiveMessage extends Service {
21
22 // @Override
23 // public int onStartCommand(Intent intent, int flags, int startId) {
24 // // TODO Auto-generated method stub
25 // return super.onStartCommand(intent, flags, startId);
26 // }
27
28 private SocketChannel client = null;
29 private InetSocketAddress isa = null;
30 private String message = "";
31
32 public void onCreate() {
33 System.out.println("----- onCreate---------");
34 super.onCreate();
35
36 ConnectToServer();
37 StartServerListener();
38
39 }
40
41 public void onDestroy() {
42 super.onDestroy();
43 DisConnectToServer();
44 }
45
46 public void onStart(Intent intent, int startId) {
47 System.out.println("----- onStart---------");
48 super.onStart(intent, startId);
49 }
50
51 /*
52 * IBinder方法 , LocalBinder 类,mBinder接口这三项用于
53 * Activity进行Service的绑定,点击发送消息按钮之后触发绑定 并通过Intent将Activity中的EditText的值
54 * 传送到Service中向服务器发送
55 */
56 public IBinder onBind(Intent intent) {
57 System.out.println("----- onBind---------");
58
59 // message = intent.getStringExtra("chatmessage");
60 // if (message.length() > 0) {
61 // SendMessageToServer(message);
62 // }
63 return mBinder;
64 }
65
66 public class LocalBinder extends Binder {
67 ReceiveMessage getService() {
68 return ReceiveMessage.this;
69 }
70 }
71
72 private final IBinder mBinder = new LocalBinder();
73
74 // 用于链接服务器端
75 public void ConnectToServer() {
76 try {
77
78 client = SocketChannel.open();
79 //isa = new InetSocketAddress("10.0.2.2", 9005);
80 isa = new InetSocketAddress("211.141.230.246", 6666);
81 client.connect(isa);
82 client.configureBlocking(false);
83
84 } catch (IOException e) {
85 // TODO Auto-generated catch block
86 e.printStackTrace();
87
88 }
89 }
90
91 // 断开与服务器端的链接
92 public void DisConnectToServer() {
93 try {
94 client.close();
95 } catch (IOException e) {
96 // TODO Auto-generated catch block
97 e.printStackTrace();
98 }
99 }
100
101 // 启动服务器端的监听线程,从Server端接收消息
102 public void StartServerListener() {
103 ServerListener a = new ServerListener();
104 a.start();
105 }
106
107 // 向Server端发送消息
108 public void SendMessageToServer(String msg) {
109
110 System.out.println("Send:" + msg);
111
112 try {
113 ByteBuffer bytebuf = ByteBuffer.allocate(1024);
114 bytebuf = ByteBuffer.wrap(msg.getBytes("UTF-8"));
115 client.write(bytebuf);
116 bytebuf.flip();
117 } catch (IOException e) {
118 // TODO Auto-generated catch block
119 e.printStackTrace();
120 System.out.println(" SendMessageToServer IOException===");
121
122 }
123 }
124
125 private void shownotification(String tab) {
126 System.out.println("shownotification=====" + tab);
127 NotificationManager barmanager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
128 Notification msg = new Notification(
129 android.R.drawable.stat_notify_chat, "A Message Coming!",
130 System.currentTimeMillis());
131 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
132 new Intent(this, AnetTest.class), PendingIntent.FLAG_ONE_SHOT);
133 msg.setLatestEventInfo(this, "Message", "Message:" + tab, contentIntent);
134 barmanager.notify(0, msg);
135 }
136 // 发送广播信息
137 private void sendMsg(String msg){
138 // 指定广播目标的 action (注:指定了此 action 的 receiver 会接收此广播)
139 Intent intent = new Intent("com.archfree.demo.msg");
140 // 需要传递的参数
141 intent.putExtra("msg", msg);
142 // 发送广播
143 this.sendBroadcast(intent);
144 }
145
146 private class ServerListener extends Thread {
147 //private ByteBuffer buf = ByteBuffer.allocate(1024);
148 public void run() {
149
150 try {
151 // 无线循环,监听服务器,如果有不为空的信息送达,则更新Activity的UI
152 while (true) {
153 ByteBuffer buf = ByteBuffer.allocate(1024);
154 //buf.clear();
155 client.read(buf);
156 buf.flip();
157 Charset charset = Charset.forName("UTF-8");
158 CharsetDecoder decoder = charset.newDecoder();
159 CharBuffer charBuffer;
160 charBuffer = decoder.decode(buf);
161 String result = charBuffer.toString();
162 if (result.length() > 0)
163 {// recvData(result);
164 sendMsg(result);
165 //System.out.println("+++++="+result);
166
167 //shownotification(result);
168 }
169
170
171 // System.out.println("++++++++++++++++++="+result);
172 }
173 } catch (CharacterCodingException e) {
174 // TODO Auto-generated catch block
175 e.printStackTrace();
176 } catch (IOException e) {
177 // TODO Auto-generated catch block
178 e.printStackTrace();
179 }
180 }
181 }
182
183 }
2
3 import java.io.IOException;
4 import java.net.InetSocketAddress;
5 import java.nio.ByteBuffer;
6 import java.nio.CharBuffer;
7 import java.nio.channels.SocketChannel;
8 import java.nio.charset.CharacterCodingException;
9 import java.nio.charset.Charset;
10 import java.nio.charset.CharsetDecoder;
11 import android.app.Notification;
12 import android.app.NotificationManager;
13 import android.app.PendingIntent;
14 import android.app.Service;
15 import android.content.Context;
16 import android.content.Intent;
17 import android.os.Binder;
18 import android.os.IBinder;
19
20 public class ReceiveMessage extends Service {
21
22 // @Override
23 // public int onStartCommand(Intent intent, int flags, int startId) {
24 // // TODO Auto-generated method stub
25 // return super.onStartCommand(intent, flags, startId);
26 // }
27
28 private SocketChannel client = null;
29 private InetSocketAddress isa = null;
30 private String message = "";
31
32 public void onCreate() {
33 System.out.println("----- onCreate---------");
34 super.onCreate();
35
36 ConnectToServer();
37 StartServerListener();
38
39 }
40
41 public void onDestroy() {
42 super.onDestroy();
43 DisConnectToServer();
44 }
45
46 public void onStart(Intent intent, int startId) {
47 System.out.println("----- onStart---------");
48 super.onStart(intent, startId);
49 }
50
51 /*
52 * IBinder方法 , LocalBinder 类,mBinder接口这三项用于
53 * Activity进行Service的绑定,点击发送消息按钮之后触发绑定 并通过Intent将Activity中的EditText的值
54 * 传送到Service中向服务器发送
55 */
56 public IBinder onBind(Intent intent) {
57 System.out.println("----- onBind---------");
58
59 // message = intent.getStringExtra("chatmessage");
60 // if (message.length() > 0) {
61 // SendMessageToServer(message);
62 // }
63 return mBinder;
64 }
65
66 public class LocalBinder extends Binder {
67 ReceiveMessage getService() {
68 return ReceiveMessage.this;
69 }
70 }
71
72 private final IBinder mBinder = new LocalBinder();
73
74 // 用于链接服务器端
75 public void ConnectToServer() {
76 try {
77
78 client = SocketChannel.open();
79 //isa = new InetSocketAddress("10.0.2.2", 9005);
80 isa = new InetSocketAddress("211.141.230.246", 6666);
81 client.connect(isa);
82 client.configureBlocking(false);
83
84 } catch (IOException e) {
85 // TODO Auto-generated catch block
86 e.printStackTrace();
87
88 }
89 }
90
91 // 断开与服务器端的链接
92 public void DisConnectToServer() {
93 try {
94 client.close();
95 } catch (IOException e) {
96 // TODO Auto-generated catch block
97 e.printStackTrace();
98 }
99 }
100
101 // 启动服务器端的监听线程,从Server端接收消息
102 public void StartServerListener() {
103 ServerListener a = new ServerListener();
104 a.start();
105 }
106
107 // 向Server端发送消息
108 public void SendMessageToServer(String msg) {
109
110 System.out.println("Send:" + msg);
111
112 try {
113 ByteBuffer bytebuf = ByteBuffer.allocate(1024);
114 bytebuf = ByteBuffer.wrap(msg.getBytes("UTF-8"));
115 client.write(bytebuf);
116 bytebuf.flip();
117 } catch (IOException e) {
118 // TODO Auto-generated catch block
119 e.printStackTrace();
120 System.out.println(" SendMessageToServer IOException===");
121
122 }
123 }
124
125 private void shownotification(String tab) {
126 System.out.println("shownotification=====" + tab);
127 NotificationManager barmanager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
128 Notification msg = new Notification(
129 android.R.drawable.stat_notify_chat, "A Message Coming!",
130 System.currentTimeMillis());
131 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
132 new Intent(this, AnetTest.class), PendingIntent.FLAG_ONE_SHOT);
133 msg.setLatestEventInfo(this, "Message", "Message:" + tab, contentIntent);
134 barmanager.notify(0, msg);
135 }
136 // 发送广播信息
137 private void sendMsg(String msg){
138 // 指定广播目标的 action (注:指定了此 action 的 receiver 会接收此广播)
139 Intent intent = new Intent("com.archfree.demo.msg");
140 // 需要传递的参数
141 intent.putExtra("msg", msg);
142 // 发送广播
143 this.sendBroadcast(intent);
144 }
145
146 private class ServerListener extends Thread {
147 //private ByteBuffer buf = ByteBuffer.allocate(1024);
148 public void run() {
149
150 try {
151 // 无线循环,监听服务器,如果有不为空的信息送达,则更新Activity的UI
152 while (true) {
153 ByteBuffer buf = ByteBuffer.allocate(1024);
154 //buf.clear();
155 client.read(buf);
156 buf.flip();
157 Charset charset = Charset.forName("UTF-8");
158 CharsetDecoder decoder = charset.newDecoder();
159 CharBuffer charBuffer;
160 charBuffer = decoder.decode(buf);
161 String result = charBuffer.toString();
162 if (result.length() > 0)
163 {// recvData(result);
164 sendMsg(result);
165 //System.out.println("+++++="+result);
166
167 //shownotification(result);
168 }
169
170
171 // System.out.println("++++++++++++++++++="+result);
172 }
173 } catch (CharacterCodingException e) {
174 // TODO Auto-generated catch block
175 e.printStackTrace();
176 } catch (IOException e) {
177 // TODO Auto-generated catch block
178 e.printStackTrace();
179 }
180 }
181 }
182
183 }
=================================================================
AndroidManifest.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3 package="com.archfree.demo" android:versionCode="1"
4 android:versionName="1.0">
5 <application android:icon="@drawable/icon" android:label="@string/app_name">
6 <activity android:name=".AnetTest" android:label="@string/app_name">
7 <intent-filter>
8 <action android:name="android.intent.action.MAIN" />
9 <category android:name="android.intent.category.LAUNCHER" />
10 </intent-filter>
11 </activity>
2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3 package="com.archfree.demo" android:versionCode="1"
4 android:versionName="1.0">
5 <application android:icon="@drawable/icon" android:label="@string/app_name">
6 <activity android:name=".AnetTest" android:label="@string/app_name">
7 <intent-filter>
8 <action android:name="android.intent.action.MAIN" />
9 <category android:name="android.intent.category.LAUNCHER" />
10 </intent-filter>
11 </activity>
- Android TCP 客户端实现
- Android TCP 客户端实现
- 客户端TCP实现简介
- netty实现tcp客户端
- android tcp客户端
- android tcp客户端 封装
- 基于Apache mina 的android 客户端tcp长连接实现
- Android上实现TCP&UDP的客户端和服务端
- WinSock客户端服务端实现--TCP
- 多线程异步TCP客户端实现
- TCP多客户端通信实现
- Python实现TCP\UDP客户端
- Android编程:UDP客户端和TCP客户端
- Android 开发TCP、UdP客户端
- Android 开发TCP、UdP客户端
- android 之TCP客户端编程
- Android Tcp客户端发送数据
- Android编程:双工tcp客户端
- [unity3d]加载模型资源
- 与 Xcode 相比,用 Adobe AIR/Flex做 iOS 开发有哪些优势和局限?
- Linux服务笔记:SSH远程登录
- 安卓真机上UDP程序收不到PC机数据包的解决方法
- Android实现TCP与UDP传输
- Android TCP 客户端实现
- VC++调试OCCI程序的关键设置
- CDH(Cloudera’s Distribution Including Apache Hadoop)简介
- 关于分区有序数据merge的解决方案
- Java和Android Http连接程序:使用java.net.URL 下载服务器图片到客户端
- Introduction to VMware vSphere Virtual SAN
- 在VC++中使用OCCI
- knn算法matlab实现
- Android 近百个项目的源代码,覆盖Android开发的每个领域