package safeluck.drive.evaluation.tcp;
|
|
import android.provider.ContactsContract;
|
import android.util.Log;
|
|
import java.io.DataOutputStream;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.io.OutputStream;
|
import java.net.Socket;
|
|
|
/**
|
* MyApplication2
|
* Created by lzw on 2019/10/21. 14:14:30
|
* 邮箱:632393724@qq.com
|
* All Rights Saved! Chongqing AnYun Tech co. LTD
|
*/
|
public class ConnectThread extends Thread {
|
|
private static final String TAG = "TCPClient";
|
private Socket mSocket = null;
|
private boolean isConnected = false;
|
private byte[] revBytes = new byte[1024];
|
private String ip;
|
private int port;
|
private InputStream inputStream ;
|
private OutputStream mOutputStream;
|
|
public ConnectThread(String ip,int port){
|
this.ip = ip;
|
this.port = port;
|
}
|
|
@Override
|
public void run() {
|
super.run();
|
try {
|
Log.i(TAG, "开始建立Socket"+ip+":"+port);
|
mSocket = new Socket(ip,port);
|
|
mOutputStream = mSocket.getOutputStream();
|
inputStream = mSocket.getInputStream();
|
isConnected = true;
|
while (isConnected){
|
int length = 0;
|
while ((length=(inputStream.read(revBytes))) != -1){
|
|
String str= new String(revBytes,"GBK");
|
Log.i(TAG, "收到消息: "+str.trim());
|
|
}
|
}
|
} catch (IOException e) {
|
Log.i(TAG, "Socket建立失败");
|
isConnected = false;
|
e.printStackTrace();
|
}
|
}
|
|
public void sendMessage(String lzw) {
|
if (mOutputStream == null){
|
Log.i(TAG, "sendMessage fail,please create socket first!!!");
|
}else{
|
|
new Thread(new SendRunnable(lzw)).start();
|
}
|
}
|
|
class SendRunnable implements Runnable{
|
private String message ;
|
public SendRunnable(String s) {
|
this.message = s;
|
}
|
|
@Override
|
public void run() {
|
try {
|
Log.i(TAG, "发送: "+message);
|
mSocket.sendUrgentData(0xff);
|
mOutputStream.write(message.getBytes("GBK"));
|
} catch (IOException e) {
|
Log.i(TAG, "发送失败");
|
e.printStackTrace();
|
}
|
}
|
}
|
}
|