hxb
2021-12-21 8b66be08179b026cb0e601733dacd43de97e5b01
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package com.hdl.sdk.socket.client;
 
 
 
import com.hdl.sdk.common.utils.ByteUtils;
import com.hdl.sdk.common.utils.ThreadToolUtils;
import com.hdl.sdk.socket.SocketBoot;
import com.hdl.sdk.socket.SocketOptions;
import com.hdl.sdk.socket.annotation.ConnectStatus;
import com.hdl.sdk.socket.codec.IHandleMessage;
import com.hdl.sdk.socket.listener.ConnectStatusListener;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
 
 
/**
 * Created by Tong on 2021/9/15.
 */
public final class TcpClient implements IClient {
 
 
    private SocketOptions socketOptions;
 
    private final String ip;
    private final int port;
 
    private Socket mSocket;
 
    private final static List<TcpClient> tcpClientList = new ArrayList();
 
    /**
     * 从连接池中找出当前IP及端口的连接客户端
     * @param ipAdderss 连接IP地址
     * @param port 连接端口
     * @return
     */
    public static TcpClient getTcpClientByIP(String ipAdderss,int port) {
        for(TcpClient tcpClient:tcpClientList){
            if(tcpClient.ip.equals(ipAdderss)&&tcpClient.port==port)
            {
                return tcpClient;
            }
        }
        return  null;
    }
 
    private byte[] readBuffer = new byte[4*1024];
 
    private TcpClient(String ip, int port, SocketOptions socketOptions) {
        this.socketOptions = socketOptions;
        this.ip = ip;
        this.port = port;
        socketOptions.setIp(ip);
        socketOptions.setPort(port);
    }
 
    public static SocketBoot init(String ip, int port, SocketOptions options) {
        return new SocketBoot(new TcpClient(ip, port, options));
    }
 
 
    @Override
    public void connect() throws Exception {
        mSocket = getSocket();
        SocketOptions options = getOptions();
        mSocket.connect(new InetSocketAddress(ip, port));
        mSocket.setTcpNoDelay(true);
        mSocket.setReuseAddress(true);
        mSocket.setKeepAlive(true);
 
        tcpClientList.add(this);
    }
 
 
 
 
    @Override
    public void disconnect() {
        if (mSocket != null) {
            try {
                mSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    @Override
    public synchronized SocketOptions getOptions() {
        if (socketOptions == null) {
            socketOptions = new SocketOptions();
        }
        return socketOptions;
    }
 
    @Override
    public void onHandleResponse() throws Exception {
        final InputStream stream = getInputStream();
        if (stream != null && getOptions() != null) {
            int len=0;
            while ( (len=getInputStream().read(readBuffer)) != -1) {
                IHandleMessage handleMessage = getOptions().getHandleMessage();
                if (handleMessage != null) {
                    byte []bytes = new byte[len];
                    System.arraycopy(readBuffer,0,bytes,0,len);
                    //完整的数据才回调
                    handleMessage.read(bytes);
                }
            }
        }
    }
 
    @Override
    public void sendMsg(byte[] msg) throws Exception {
        final OutputStream outputStream = getOutStream();
        if (outputStream != null && getOptions() != null) {
            try {
                IHandleMessage handleMessage = getOptions().getHandleMessage();
                handleMessage.write(handleMessage.write(msg));
                getOutStream().write(msg);
 
            } finally {
                outputStream.flush();
            }
        }
    }
 
 
    /**
     * 处理连接状态
     */
    public void onConnectStatus(int status) {
        ThreadToolUtils.getInstance().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final List<ConnectStatusListener> list = getOptions().getConnectStatusListener();
                if (list != null && !list.isEmpty()) {
                    for (ConnectStatusListener listener : list) {
                        switch (status) {
                            case ConnectStatus
                                    .CONNECTING:
                                listener.onConnecting();
                                break;
                            case ConnectStatus
                                    .CONNECTED:
                                listener.onConnected();
                                break;
                            case ConnectStatus
                                    .DISCONNECT:
                                listener.onConnectFailed();
                                break;
                        }
                    }
                }
            }
        });
    }
 
 
    private synchronized Socket getSocket() {
        return new Socket();
    }
 
    private InputStream getInputStream() {
        if (mSocket != null && mSocket.isConnected() && !mSocket.isClosed()) {
            try {
                return mSocket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
 
 
    private OutputStream getOutStream() {
        if (mSocket != null && mSocket.isConnected() && !mSocket.isClosed()) {
            try {
                return mSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
 
 
}