本文实例讲述了Android编程实现TCP客户端的方法。分享给大家供大家参考,具体如下:
因为项目上需要实现一个TCP Client 端;在网上找好多例子基本上都是阻塞方式完成;
我的实现例子:由Activity 及sever 来实现,在sever 创建一个线程来监听接受数据。收到数据,通过广播发送给Activity;
服务端我没有去实现,你可以下载TCP Socket 调试工具v2.2;创建个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的内部类实现来连接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;
// 实现一个 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);
// 实例化自定义的 BroadcastReceiver
mReceiver = new UpdateReceiver();
IntentFilter filter = new IntentFilter();
// 为 BroadcastReceiver 指定 action ,使之用于接收同 action 的广播
filter.addAction("com.archfree.demo.msg");
// 以编程方式注册 BroadcastReceiver 。配置方式注册 BroadcastReceiver 的例子见
// AndroidManifest.xml 文件
// 一般在 OnStart 时注册,在 OnStop 时取消注册
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和本地服务交互,需要使用bind和unbind方法
* */
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unbindService(serviceConnection);
unregisterReceiver(mReceiver);
}
}
ReceiveMessage.java 参考网络资源,修改;
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接口这三项用于
* Activity进行Service的绑定,点击发送消息按钮之后触发绑定 并通过Intent将Activity中的EditText的值
* 传送到Service中向服务器发送
*/
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();
// 用于链接服务器端
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();
}
}
// 断开与服务器端的链接
public void DisConnectToServer() {
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 启动服务器端的监听线程,从Server端接收消息
public void StartServerListener() {
ServerListener a = new ServerListener();
a.start();
}
// 向Server端发送消息
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);
}
// 发送广播信息
private void sendMsg(String msg){
// 指定广播目标的 action (注:指定了此 action 的 receiver 会接收此广播)
Intent intent = new Intent("com.archfree.demo.msg");
// 需要传递的参数
intent.putExtra("msg", msg);
// 发送广播
this.sendBroadcast(intent);
}
private class ServerListener extends Thread {
//private ByteBuffer buf = ByteBuffer.allocate(1024);
public void run() {
try {
// 无线循环,监听服务器,如果有不为空的信息送达,则更新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>
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android通信方式总结》、《Android调试技巧与常见问题解决方法汇总》、《Android开发入门与进阶教程》、《Android多媒体操作技巧汇总(音频,视频,录音等)》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。
本文向大家介绍Android编程实现TCP、UDP客户端通信功能示例,包括了Android编程实现TCP、UDP客户端通信功能示例的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Android编程实现TCP、UDP客户端通信功能。分享给大家供大家参考,具体如下: 在进行Android开发的过程中,免不了,要开发TCP/UDP通讯的程序,下面这两段代码,分别介绍了TCP/UCP通过的一个实例
利用 select 实现的 tcp 客户端 利用 select 实现的 tcp 客户端 源码/* * Copyright (c) 2006-2018, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * *//* 程序清单:利用 selec
创建 TCP 客户端 最简单的方法来创建一个 TCP 客户端,使用默认选项如下所示: NetClient client = vertx.createNetClient(); 配置 TCP 客户端 如果你不想使用默认值,则创建TCP 客户端时,通过传入NetClientOptions实例可以配置: NetClientOptions options = new NetClientOptions().s
我不熟悉JAVA/Android TCP连接。我尝试实现一个TCP服务器,如下代码所示。 当我通过socket=serverSocket获取套接字时,我可以向客户端发送消息。accept() -----------------------------问题----------------------------- 我需要为客户端设置不同的端口吗?但是如何从多客户端获取多个套接字呢?
有没有我可以参考的示例应用程序用于Android上的SAML交互?有人在Android上成功移植/使用了OpenSAML吗? 我正在尝试编写一个简单的应用程序,它将(而不是浏览器重定向)使用本机API来执行SAML身份验证。 还有一些指向测试环境的指针,我可以在其中测试SAML客户机,这会有所帮助。
tcp 客户端例程 tcp 客户端例程 源码/* * Copyright (c) 2006-2018, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * *//* * 程序清单:tcp 客户端 * * 这是一个 tcp 客户端的例程 *
Coroutine\Client提供了TCP、UDP、unixSocket传输协议的Socket客户端封装代码,使用时仅需new Swoole\Coroutine\Client即可。 实现原理 Coroutine\Client的所有涉及网络请求的方法,Swoole都会进行协程调度,业务层无需感知 使用方法和Client同步模式方法完全一致 connect超时设置同时作用于Connect和Recv、
我使用这个(Android TCP连接增强的)教程来创建简单的JAVA TCPServer和Android TCPClient。它工作得很好,但使用这段代码我只能同时将一个设备连接到服务器。我必须更改什么才能连接多个设备?