endian11
2019-11-25 6ee087d628cb1107e1f741d15281ccd4c4dcc838
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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();
            }
        }
    }
}