Skip to content

Commit 87da444

Browse files
committed
project init
1 parent e2595c0 commit 87da444

File tree

4 files changed

+298
-2
lines changed

4 files changed

+298
-2
lines changed

build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ buildscript {
88
}
99
dependencies {
1010
classpath 'com.android.tools.build:gradle:3.0.1'
11-
11+
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
1212

1313
// NOTE: Do not place your application dependencies here; they belong
1414
// in the individual module build.gradle files

tcpsocketlib/build.gradle

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
apply plugin: 'com.android.library'
2-
2+
apply plugin: 'com.github.dcendents.android-maven'
3+
group='com.github.lp0int'
34
android {
45
compileSdkVersion 26
56

Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
package com.lpoint.tcpsocketlib;
2+
3+
import android.util.Log;
4+
5+
import java.io.DataInputStream;
6+
import java.io.InputStream;
7+
import java.io.PrintWriter;
8+
import java.net.Socket;
9+
import java.util.concurrent.BlockingQueue;
10+
import java.util.concurrent.ExecutorService;
11+
import java.util.concurrent.LinkedBlockingQueue;
12+
import java.util.concurrent.ThreadPoolExecutor;
13+
import java.util.concurrent.TimeUnit;
14+
15+
/**
16+
* @author 季白
17+
* create time 2018/8/10.
18+
*/
19+
20+
public class TcpClient {
21+
public static final String TAG = "TcpClient";
22+
/**
23+
* 连接的服务器IP地址
24+
*/
25+
private String serverIP = "";
26+
/**
27+
* 连接的socket服务端口
28+
*/
29+
private int serverPort = -1;
30+
private PrintWriter pw;
31+
private InputStream is;
32+
private DataInputStream dis;
33+
private boolean isRun = false;
34+
private byte buff[] = new byte[4096];
35+
private String rcvMsg;
36+
private Socket socket;
37+
private int rcvLen;
38+
/**
39+
* socket的timeout时间,默认为0
40+
*/
41+
private int soTimeOut = 0;
42+
private Runnable msgRun;
43+
private Runnable connRun;
44+
private Runnable sendMsgRun;
45+
/**
46+
* socket接受消息的编码格式,默认"utf-8"
47+
*/
48+
private String charsetName = "utf-8";
49+
/**
50+
* TCP连接的状态监听
51+
*/
52+
private TcpSocketListener tcpSocketListener;
53+
private int numberOfCores = Runtime.getRuntime().availableProcessors();
54+
/**
55+
* 额外线程空状态生存时间
56+
*/
57+
private int keepAliveTime = 1;
58+
private BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>();
59+
private boolean needReConn = false;
60+
private int reConnTime = 10;
61+
ExecutorService executorService = new ThreadPoolExecutor(numberOfCores,
62+
numberOfCores * 2, keepAliveTime, TimeUnit.SECONDS, taskQueue);
63+
64+
public TcpClient(String serverIp, int port) {
65+
this.serverIP = serverIp;
66+
this.serverPort = port;
67+
tcpSocketListener = new TcpSocketListener() {
68+
@Override
69+
public void onConnException(Exception e) {
70+
Log.e(TAG, e.toString());
71+
}
72+
73+
@Override
74+
public void onMessage(String s) {
75+
Log.i(TAG, s);
76+
}
77+
78+
@Override
79+
public void onListenerException(Exception e) {
80+
Log.e(TAG, e.toString());
81+
}
82+
83+
@Override
84+
public void onSendMsgSuccess(String msg) {
85+
86+
}
87+
88+
@Override
89+
public void onSendMsgException(Exception e) {
90+
Log.e(TAG, e.toString());
91+
}
92+
93+
@Override
94+
public void onCloseException(Exception e) {
95+
Log.e(TAG, e.toString());
96+
}
97+
};
98+
}
99+
100+
/**
101+
* 设置连接的socket服务器IP
102+
* @param serverIP
103+
*/
104+
public void setServerIP(String serverIP) {
105+
this.serverIP = serverIP;
106+
}
107+
108+
/**
109+
* 设置连接的socket服务端口
110+
* @param serverPort
111+
*/
112+
113+
public void setServerPort(int serverPort) {
114+
this.serverPort = serverPort;
115+
}
116+
117+
/**
118+
* 设置soTimeOut
119+
* @param soTimeOut
120+
*/
121+
public void setSoTimeOut(int soTimeOut) {
122+
this.soTimeOut = soTimeOut;
123+
}
124+
125+
/**
126+
* 设置socket接收字符的格式,默认"utf-8"
127+
* @param charsetName
128+
*/
129+
public void setCharsetName(String charsetName) {
130+
this.charsetName = charsetName;
131+
}
132+
133+
/**
134+
* 设置是否需要断开后重新连接
135+
* @param needReConn
136+
*/
137+
public void setNeedReConn(boolean needReConn) {
138+
this.needReConn = needReConn;
139+
}
140+
141+
/**
142+
* 设置socket断开后重新连接间隔时间
143+
*
144+
* @param reConnTime 重连间隔时间 单位 秒
145+
*/
146+
public void setReConnTime(int reConnTime) {
147+
this.reConnTime = reConnTime;
148+
}
149+
150+
/**
151+
* 设置socket的各种状态的回掉
152+
* @param tcpSocketListener
153+
*/
154+
public void setTcpSocketListener(TcpSocketListener tcpSocketListener) {
155+
this.tcpSocketListener = tcpSocketListener;
156+
}
157+
158+
public void startConn() {
159+
connRun = new Runnable() {
160+
@Override
161+
public void run() {
162+
if (isRun) {
163+
tcpSocketListener.onConnException(new Exception("已经有一个socket连接了"));
164+
return;
165+
}
166+
try {
167+
socket = new Socket(serverIP, serverPort);
168+
socket.setSoTimeout(soTimeOut);
169+
pw = new PrintWriter(socket.getOutputStream(), true);
170+
is = socket.getInputStream();
171+
dis = new DataInputStream(is);
172+
startListen();
173+
} catch (Exception e) {
174+
tcpSocketListener.onConnException(e);
175+
closeTcpSocket();
176+
}
177+
}
178+
};
179+
executorService.execute(connRun);
180+
}
181+
182+
private void startListen() {
183+
if (isRun) {
184+
tcpSocketListener.onListenerException(new Exception("当前消息监听尚未停止,无法执行startListen()"));
185+
return;
186+
}
187+
if (socket == null || pw == null || is == null) {
188+
tcpSocketListener.onListenerException(new Exception("socket初始化失败,无法执行startListen()"));
189+
return;
190+
}
191+
isRun = true;
192+
msgRun = new Runnable() {
193+
@Override
194+
public void run() {
195+
while (isRun) {
196+
try {
197+
rcvLen = dis.read(buff);
198+
rcvMsg = new String(buff, 0, rcvLen, charsetName);
199+
tcpSocketListener.onMessage(rcvMsg);
200+
} catch (Exception e) {
201+
tcpSocketListener.onListenerException(e);
202+
closeTcpSocket();
203+
}
204+
}
205+
}
206+
};
207+
executorService.execute(msgRun);
208+
}
209+
210+
public void sendMsg(final String msg) {
211+
sendMsgRun = new Runnable() {
212+
@Override
213+
public void run() {
214+
try {
215+
pw.println(msg);
216+
pw.flush();
217+
tcpSocketListener.onSendMsgSuccess(msg);
218+
} catch (Exception e) {
219+
tcpSocketListener.onSendMsgException(e);
220+
}
221+
}
222+
};
223+
executorService.execute(sendMsgRun);
224+
}
225+
226+
public void closeTcpSocket() {
227+
try {
228+
isRun = false;
229+
pw.close();
230+
is.close();
231+
dis.close();
232+
socket.close();
233+
} catch (Exception e) {
234+
tcpSocketListener.onCloseException(e);
235+
} finally {
236+
if (needReConn && !isRun) {
237+
try {
238+
Thread.sleep(reConnTime * 1000);
239+
startConn();
240+
} catch (Exception e) {
241+
Log.e(TAG, e.getMessage());
242+
}
243+
}
244+
}
245+
}
246+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.lpoint.tcpsocketlib;
2+
3+
/**
4+
* @author 季白
5+
* 创建时间 2018/8/10.
6+
*/
7+
8+
public interface TcpSocketListener {
9+
/**
10+
* 发起TCP连接时报出的异常
11+
*
12+
* @param e
13+
*/
14+
void onConnException(Exception e);
15+
16+
/**
17+
* 当TCP通道收到消息时执行此回调
18+
* 需要注意此回掉会在异步线程中执行,如果需要更新UI则需要runOnUiThread
19+
*
20+
* @param s
21+
*/
22+
void onMessage(String s);
23+
24+
/**
25+
* 当TCP消息监听时遇到异常,从这里抛出
26+
*
27+
* @param e
28+
*/
29+
void onListenerException(Exception e);
30+
31+
/**
32+
* 当sendMsg()方法成功执行完毕后,执行此方法
33+
* @param s
34+
*/
35+
void onSendMsgSuccess(String s);
36+
37+
/**
38+
* 发送消息时遇到异常,从这里抛出
39+
* @param e
40+
*/
41+
void onSendMsgException(Exception e);
42+
43+
/**
44+
* 当TCP连接断开时遇到异常,从这里抛出
45+
*
46+
* @param e
47+
*/
48+
void onCloseException(Exception e);
49+
}

0 commit comments

Comments
 (0)