client.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="接收到的信息" /> <TextView
android:id="@+id/tv1"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_weight="0.25"
android:text="" /> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="请输入发送内容" /> <EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" > <requestFocus />
</EditText> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="设置" /> </LinearLayout> </LinearLayout>

client.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException; import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView; public class Client extends Activity {
private String TAG = "===Client===";
private String TAG1 = "===Send===";
private TextView tv1 = null;
Handler mhandler;
Handler mhandlerSend;
boolean isRun = true;
EditText edtsendms;
Button btnsend;
private String sendstr = "";
SharedPreferences sp;
Button btnSetting;
private Context ctx;
Socket socket;
PrintWriter out;
BufferedReader in;
SocThread socketThread; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
tv1 = (TextView) findViewById(R.id.tv1);
btnsend = (Button) findViewById(R.id.button1);
ctx = Client.this;
edtsendms = (EditText) findViewById(R.id.editText1);
btnSetting = (Button) findViewById(R.id.button2);
mhandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
MyLog.i(TAG, "mhandler接收到msg=" + msg.what);
if (msg.obj != null) {
String s = msg.obj.toString();
if (s.trim().length() > 0) {
MyLog.i(TAG, "mhandler接收到obj=" + s);
MyLog.i(TAG, "开始更新UI");
tv1.append("Server:" + s);
MyLog.i(TAG, "更新UI完毕");
} else {
Log.i(TAG, "没有数据返回不更新");
}
}
} catch (Exception ee) {
MyLog.i(TAG, "加载过程出现异常");
ee.printStackTrace();
}
}
};
mhandlerSend = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
MyLog.i(TAG, "mhandlerSend接收到msg.what=" + msg.what);
String s = msg.obj.toString();
if (msg.what == 1) {
tv1.append("\n ME: " + s + " 发送成功");
} else {
tv1.append("\n ME: " + s + " 发送失败");
}
} catch (Exception ee) {
MyLog.i(TAG, "加载过程出现异常");
ee.printStackTrace();
}
}
};
startSocket();
btnsend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 发送数据
MyLog.i(TAG, "准备发送数据");
sendstr = edtsendms.getText().toString().trim();
socketThread.Send(sendstr); }
});
btnSetting.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// 跳转到设置界面
Intent intent = new Intent();
intent.setClass(Client.this, Setting.class);
MyLog.i(TAG, "跳转至设置界面");
ctx.startActivity(intent);// 打开新界面 }
}); } public void startSocket() {
socketThread = new SocThread(mhandler, mhandlerSend, ctx);
socketThread.start();
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.client, menu);
return true;
} private void stopSocket() {
socketThread.isRun = false;
socketThread.close();
socketThread = null;
MyLog.i(TAG, "Socket已终止");
} @Override
protected void onStart() {
super.onStart();
Log.e(TAG, "start onStart~~~");
} @Override
protected void onRestart() {
super.onRestart();
Log.e(TAG, "start onRestart~~~");
startSocket();
} @Override
protected void onResume() {
super.onResume();
Log.e(TAG, "start onResume~~~");
} @Override
protected void onPause() {
super.onPause();
Log.e(TAG, "start onPause~~~");
} @Override
protected void onStop() {
super.onStop();
Log.e(TAG, "start onStop~~~");
stopSocket();
} @Override
protected void onDestroy() {
super.onDestroy();
Log.e(TAG, "start onDestroy~~~"); } }

socket线程:SocThread.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException; import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log; public class SocThread extends Thread {
private String ip = "10.0.0.113";
private int port = 13000;
private String TAG = "socket thread";
private int timeout = 10000; public Socket client = null;
PrintWriter out;
BufferedReader in;
public boolean isRun = true;
Handler inHandler;
Handler outHandler;
Context ctx;
private String TAG1 = "===Send===";
SharedPreferences sp; public SocThread(Handler handlerin, Handler handlerout, Context context) {
inHandler = handlerin;
outHandler = handlerout;
ctx = context;
MyLog.i(TAG, "创建线程socket");
} /**
* 连接socket服务器
*/
public void conn() { try {
initdate();
Log.i(TAG, "连接中……");
client = new Socket(ip, port);
client.setSoTimeout(timeout);// 设置阻塞时间
MyLog.i(TAG, "连接成功");
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
client.getOutputStream())), true);
MyLog.i(TAG, "输入输出流获取成功");
} catch (UnknownHostException e) {
MyLog.i(TAG, "连接错误UnknownHostException 重新获取");
e.printStackTrace();
conn();
} catch (IOException e) {
MyLog.i(TAG, "连接服务器io错误");
e.printStackTrace();
} catch (Exception e) {
MyLog.i(TAG, "连接服务器错误Exception" + e.getMessage());
e.printStackTrace();
}
} public void initdate() {
sp = ctx.getSharedPreferences("SP", ctx.MODE_PRIVATE);
ip = sp.getString("ipstr", ip);
port = Integer.parseInt(sp.getString("port", String.valueOf(port)));
MyLog.i(TAG, "获取到ip端口:" + ip + ";" + port);
} /**
* 实时接受数据
*/
@Override
public void run() {
MyLog.i(TAG, "线程socket开始运行");
conn();
MyLog.i(TAG, "1.run开始");
String line = "";
while (isRun) {
try {
if (client != null) {
MyLog.i(TAG, "2.检测数据");
while ((line = in.readLine()) != null) {
MyLog.i(TAG, "3.getdata" + line + " len=" + line.length());
MyLog.i(TAG, "4.start set Message");
Message msg = inHandler.obtainMessage();
msg.obj = line;
inHandler.sendMessage(msg);// 结果返回给UI处理
MyLog.i(TAG1, "5.send to handler");
} } else {
MyLog.i(TAG, "没有可用连接");
conn();
}
} catch (Exception e) {
MyLog.i(TAG, "数据接收错误" + e.getMessage());
e.printStackTrace();
}
}
} /**
* 发送数据
*
* @param mess
*/
public void Send(String mess) {
try {
if (client != null) {
MyLog.i(TAG1, "发送" + mess + "至"
+ client.getInetAddress().getHostAddress() + ":"
+ String.valueOf(client.getPort()));
out.println(mess);
out.flush();
MyLog.i(TAG1, "发送成功");
Message msg = outHandler.obtainMessage();
msg.obj = mess;
msg.what = 1;
outHandler.sendMessage(msg);// 结果返回给UI处理
} else {
MyLog.i(TAG, "client 不存在");
Message msg = outHandler.obtainMessage();
msg.obj = mess;
msg.what = 0;
outHandler.sendMessage(msg);// 结果返回给UI处理
MyLog.i(TAG, "连接不存在重新连接");
conn();
} } catch (Exception e) {
MyLog.i(TAG1, "send error");
e.printStackTrace();
} finally {
MyLog.i(TAG1, "发送完毕"); }
} /**
* 关闭连接
*/
public void close() {
try {
if (client != null) {
MyLog.i(TAG, "close in");
in.close();
MyLog.i(TAG, "close out");
out.close();
MyLog.i(TAG, "close client");
client.close();
}
} catch (Exception e) {
MyLog.i(TAG, "close err");
e.printStackTrace();
} }
}

说明:

1.接收数据并读取时的推荐使用BufferedReader 会比直接读取要效率高些
2.BufferedReader默认大小:8192个字节=84Mbit,utf-8下等于4596个字符 一般足够用了
3.接收数据使用的是ReadLine,实际测试中直接发送无法接收到数据,后来发现必须在发送数据的末尾加入'\n'换行符才能识别到,目前ReadLine是行读取没有了行标志无法读取到数据
4.中文乱码问题 字符编码格式的问题 可以使用GB2312格式解析
  in= new BufferedReader(new InputStreamReader(socket.getInputStream(), "gb2312"));

源码下载:下载地址

Android笔记:Socket客户端收发数据的更多相关文章

  1. 多线程socket UDP收发数据

    多线程socket收发数据 from threading import Thread from socket import * def sendData(): while True: sendInfo ...

  2. udp客户端收发数据流程

    1.创建客户端socket开始进行通讯.2.这时服务端应该先启动,并在知道服务端的ip以及端口号的时候才能进行通讯.3.本地不需要绑定ip以及端口号,在用此套接字对象发送消息的时候会自动分配活动端口( ...

  3. HTML5学习笔记之客户端存储数据方法:localStorage(),sessionStorage()

    HTML5提供了两种在客户端存储数据的新方法: localStorage():没有时间限制的数据存储 sessionStorage():针对一个session的数据存储 下面的一个例子用localSt ...

  4. Android之socket客户端

    接收数据不要用readline(),用read() Socket mSocket = new Socket("192.168.1.100", 8888); DataInputStr ...

  5. Android笔记——Socket通信实现简单聊天室

    两部分,客户端和服务端 ---------------------------------------------------------------- 客户端  1.为防止ANR异常,互联网连接可用 ...

  6. Android笔记——Activity中的数据传递案例(用户注冊)

    1.创建程序activity_main: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/andro ...

  7. 2、 Spark Streaming方式从socket中获取数据进行简单单词统计

    Spark 1.5.2 Spark Streaming 学习笔记和编程练习 Overview 概述 Spark Streaming is an extension of the core Spark ...

  8. Android—基于Socket与上传图片到客户端

    最近项目中需要客户端和Socket互相传递数据时候需要相互传递图片所以做下总结以免以后忘记,也希望给大家带来帮助. 先上客户端的代码: 根据图片名称上传照相机中单个照片(此方法为自己封装) 参数所代表 ...

  9. Android笔记——Android中数据的存储方式(二)

    我们在实际开发中,有的时候需要储存或者备份比较复杂的数据.这些数据的特点是,内容多.结构大,比如短信备份等.我们知道SharedPreferences和Files(文本文件)储存这种数据会非常的没有效 ...

随机推荐

  1. Catching Fish[HDU1077]

    Catching Fish Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)To ...

  2. 【BZOJ】1069: [SCOI2007]最大土地面积(凸包+旋转卡壳)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1069 显然这四个点在凸包上,然后枚举两个点找上下最大的三角形即可. 找三角形表示只想到三分QAQ.. ...

  3. BZOJ3809: Gty的二逼妹子序列

    Description Autumn和Bakser又在研究Gty的妹子序列了!但他们遇到了一个难题.   对于一段妹子们,他们想让你帮忙求出这之内美丽度∈[a,b]的妹子的美丽度的种类数.   为了方 ...

  4. cJSON应用举例

    //在网上查了不少cJSON,结果只找到c语言字符串转换到JSON的实例,想转回来结果没有实例.自己琢磨了一个下午才敢下手.下面把转来转去的代码贴上. //百度网盘的 CJSON 实例源码 地址 ht ...

  5. 静态页分页功能js代码

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  6. Html - Footer

    通用的Footer代码片段 <style> #footer { padding: 20px; text-align: center; background-color: #666; bor ...

  7. ASP.NET WEB API的服务托管(Self-HOST)

    如果我们想对外发布RESTful API,可以基于ASP.NET来构建Restful APIs,但需要部署IIS吗?答案是不必.你可以把它托管到一个Windows Service.具体如何把WEB A ...

  8. [转]Multiple outputs from T4 made easy

    本文转自:http://damieng.com/blog/2009/01/22/multiple-outputs-from-t4-made-easy One of the things I wante ...

  9. 获取某个Group中所有对象的DisplayName

    $SANs = Get-ADGroupMember -Identity "CN=gAPCHN-HGZ-IE10-Users,OU=Groups,OU=Hangzhou - China,OU= ...

  10. NBUT 1602 Mod Three(线段树单点更新区间查询)

    [1602] Mod Three 时间限制: 5000 ms 内存限制: 65535 K 问题描述 Please help me to solve this problem, if so, Liang ...