package com.test.ceshi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
public class ClientThread implements Runnable {
private Socket s;
// 定义向UI线程发送消息的Handler对象
Handler handler;
// 定义接收UI线程的Handler对象
Handler revHandler;
// 该线程处理Socket所对用的输入输出流
BufferedReader br = null;
OutputStream os = null;
String IP=”192.168.1.199″;
int port=5000;
int timeout=3000;
public ClientThread(Handler handler) {
this.handler = handler;
}
public ClientThread(Handler handler,String Ip,int port,int timeout) {
this.handler = handler;
this.IP=Ip;
this.port=port;
this.timeout=timeout;
}
@Override
public void run() {
s = new Socket();
try {
s.connect(new InetSocketAddress(IP,port ),timeout );
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
os = s.getOutputStream();
{
Message msg = new Message();
msg.what = 0x123;
msg.obj = “已连接”;
handler.sendMessage(msg);
}
// 启动一条子线程来读取服务器相应的数据
Thread rcvThread= new Thread() {
@Override
public void run() {
String content = null;
// 不断的读取Socket输入流的内容
try {
while ((content = br.readLine()) != null) {
// 每当读取到来自服务器的数据之后,发送的消息通知程序
// 界面显示该数据
Message msg = new Message();
msg.what = 0x456;
msg.obj = content;
handler.sendMessage(msg);
}
} catch (IOException io) {
io.printStackTrace();
}
}
};
rcvThread.setDaemon(true);
rcvThread.start();
// 为当前线程初始化Looper
Looper.prepare();
// 创建revHandler对象
revHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 接收到UI线程的中用户输入的数据
if (msg.what == 0x345) {
// 将用户在文本框输入的内容写入网络
try {
if(!s.isClosed()){
os.write((msg.obj.toString() + “\r\n”)
.getBytes(“gbk”));
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 接收到UI线程的中用户输入的数据
if (msg.what == 0x678) {
// 断开连接
try {
os.close();
s.close();
Message ms = new Message();
ms.what = 0x123;
ms.obj = “网络断开”;
handler.sendMessage(ms);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
// 启动Looper
Looper.loop();
} catch (SocketTimeoutException e) {
Message msg = new Message();
msg.what = 0x123;
msg.obj = “网络连接超时!”;
handler.sendMessage(msg);
} catch (IOException io) {
io.printStackTrace();
}
}
}
40
所以你可以考虑两种方式:
一种是在Service里边去创建Socket,用广播的方式或Intent和service通信。
二是用单例的形式管理Socket,在一个Activity创建以后,可以通过单例添加收到数据的回调或发送数据。