安卓端子线程请求socket
package yskj.buletooth;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import util.L;
/**
* Created by admin on 2016/3/21.
*/
public class ServerThread extends Thread{
private final static String IP = "192.168.0.2";
private final static int PORT = 30001;
private final static int TIME_OUT = 5000;
private boolean isPause = false;
private boolean isClose = false;
private List<String> loopList = new ArrayList<String>();
private ServerThread(){
}
private static ServerThread single = null;
public synchronized static ServerThread getInstance() {
if (single == null) {
single = new ServerThread();
}
return single;
}
public synchronized void addString(String str) {
loopList.add(str);
this.notify();
}
/**
* 暂停线程
*/
public synchronized void onThreadPause() {
isPause = true;
}
/**
* 线程等待,不提供给外部调用
*/
private void onThreadWait() {
try {
synchronized (this) {
this.wait();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 线程继续运行
*/
public synchronized void onThreadResume() {
isPause = false;
this.notify();
}
/**
* 关闭线程
*/
public synchronized void closeThread() {
try {
notify();
setClose(true);
interrupt();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isClose() {
return isClose;
}
public void setClose(boolean isClose) {
this.isClose = isClose;
}
private ThreadCallBack callBack;
public void setCallBack(ThreadCallBack callBack)
{
this.callBack = callBack;
}
@Override
public void run() {
super.run();
try {
while (!isClose && !isInterrupted())
{
if ( !isPause){
Socket socket = new Socket();
socket.connect(new InetSocketAddress(IP, PORT), TIME_OUT);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
BufferedReader bff = new BufferedReader(new InputStreamReader(in));
String line = null;
String buffer = "";
while ((line = bff.readLine()) != null) {
buffer = line + buffer;
}
out.write(("android has recever - " + System.currentTimeMillis()).getBytes("utf-8"));
out.flush();
callBack.response(buffer);
bff.close();
out.close();
socket.close();
}else{
onThreadWait();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public interface ThreadCallBack
{
void response(String response);
}
}