QpushClient.java 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. package com.uas.standard_esop.util;
  2. import android.os.Handler;
  3. import android.util.Log;
  4. import com.uas.standard_esop.util.tcp.SocketConfig;
  5. import java.io.BufferedReader;
  6. import java.io.BufferedWriter;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9. import java.io.OutputStreamWriter;
  10. import java.io.PrintWriter;
  11. import java.net.InetSocketAddress;
  12. import java.net.Socket;
  13. /**
  14. * Created by cjh-sail on 2022-11-25
  15. */
  16. public class QpushClient implements Runnable {
  17. protected static QpushClient mInstance;
  18. protected Handler mHandler;
  19. protected InetSocketAddress mAddress;
  20. protected String TAG = "QpushClient";
  21. private final int TIME_OUT = 5 * 1000;
  22. //巡检周期
  23. private final int CHECK_PERIOD = 2 * 1000;
  24. //连接尝试间隔时间
  25. private final int CONNECT_PERIOD = 30 * 1000;
  26. private final int HEARTBEART_PERIOD = 10 * 1000;
  27. //若连接失败或响应失败,则尝试次数为9,若仍无效,则不再尝试
  28. private final int CONNECT_TRY_TIMES = 9;
  29. //连接尝试次数
  30. private int mConnectCount;
  31. private static Socket mClientSocket;
  32. String mHost;
  33. int mPort;
  34. //设置是否去读取数据
  35. boolean isStartRecieveMsg = false;
  36. //开启心跳检测
  37. boolean isKeepHeartBeat = false;
  38. private QpushClient(Handler handler) {
  39. mHandler = handler;
  40. }
  41. public static QpushClient getInstance(Handler handler) {
  42. if (mInstance == null) {
  43. mInstance = new QpushClient(handler);
  44. }
  45. return mInstance;
  46. }
  47. public void init(String host, int port) {
  48. mHost = host;
  49. mPort = port;
  50. new Thread(this).start();
  51. }
  52. @Override
  53. public void run() {
  54. mAddress = new InetSocketAddress(mHost, mPort);
  55. if (mClientSocket == null) {
  56. mClientSocket = new Socket();
  57. }
  58. //尝试连接,若未连接,则设置尝试次数
  59. // while (!mClientSocket.isConnected() && mConnectCount < CONNECT_TRY_TIMES) {
  60. // connect();
  61. // if (!mClientSocket.isConnected()) {
  62. // mConnectCount++;
  63. // sleep(CONNECT_PERIOD);
  64. //
  65. // } else {
  66. // mConnectCount = 0;//连接上,则恢复置0
  67. // }
  68. // }
  69. // sendMsg("111");
  70. if (!mClientSocket.isConnected()||mClientSocket==null){
  71. connect();
  72. return;
  73. }
  74. if (mClientSocket.isConnected()) {
  75. isStartRecieveMsg = true;
  76. isKeepHeartBeat = true;
  77. Log.e("mClinentSockets1=====",mClientSocket.isConnected()+"");
  78. //开始登陆
  79. // sendMsg("login");
  80. recvMsg(2);
  81. keepHeartBeat();
  82. }else {
  83. connect();
  84. recvMsg(1);
  85. }
  86. }
  87. public static boolean isTcpConnectionSuccessful(String host, int port) {
  88. try {
  89. mClientSocket = new Socket(host, port);
  90. mClientSocket.close(); // 立即关闭连接
  91. return true;
  92. } catch (Exception e) {
  93. return false;
  94. }
  95. }
  96. private void connect() {
  97. try {
  98. mClientSocket.connect(mAddress);
  99. } catch (Exception e) {
  100. e.printStackTrace();
  101. Log.e(TAG, "mClientSocket.connect fail " + e.getMessage());
  102. if (e.getMessage().equals("Socket closed")){
  103. onDestory();
  104. recvMsg(1);
  105. }
  106. }
  107. }
  108. /**
  109. * 心跳维护
  110. */
  111. private void keepHeartBeat() {
  112. //设置心跳频率,启动心跳
  113. while(isKeepHeartBeat){
  114. // sendMsg("我是心跳包");
  115. sleep(HEARTBEART_PERIOD);
  116. }
  117. }
  118. BufferedWriter mWriter;
  119. BufferedReader mReader;
  120. /**
  121. * 不断的检测是否有服务器推送的数据过来
  122. */
  123. public void recvMsg(int ports) {
  124. if (ports==1){
  125. isStartRecieveMsg=false;
  126. return;
  127. }
  128. // while (mClientSocket != null && mClientSocket.isConnected() && !mClientSocket.isClosed()) {
  129. try {
  130. mReader = new BufferedReader(new InputStreamReader(mClientSocket.getInputStream(), SocketConfig.GBK));
  131. // while (isStartRecieveMsg) {
  132. if (mReader.ready()) {
  133. /*读取一行字符串,读取的内容来自于客户机
  134. reader.readLine()方法是一个阻塞方法,
  135. 从调用这个方法开始,该线程会一直处于阻塞状态,
  136. 直到接收到新的消息,代码才会往下走*/
  137. // String data = mReader.readLine();
  138. char[] getData = new char[9999999];
  139. // mReader.read(getData, 0, getData.length);
  140. int count = 0;
  141. // String data = String.valueOf(getData);
  142. //handler发送消息,在handleMessage()方法中接收
  143. // UTF-8:JAVAN寰堝睂ÌÆkѷ㱾拌w��Ꙙ@ 先转码,再去除不可见字符
  144. // String replaceAllRds = data.replaceAll("�", "");
  145. // Log.e("data=====",data);
  146. StringBuffer sb = new StringBuffer();
  147. while ((count = mReader.read(getData,0,getData.length))>=-1) {
  148. sb.append(getData,0, count);
  149. break;
  150. }
  151. String datas = sb.toString();
  152. handlerMsg(datas);
  153. // onDestory();
  154. // return;
  155. Thread.sleep(5000);
  156. onDestory();
  157. }
  158. // mClientSocket.setReuseAddress(true);
  159. } catch (Exception ex) {
  160. ex.printStackTrace();
  161. }
  162. // sleep(200);
  163. // }
  164. // if (!mClientSocket.isConnected()) {
  165. // try {
  166. // mClientSocket.setReuseAddress(true);
  167. // connect();
  168. // recvMsg(1);
  169. // } catch (SocketException e) {
  170. // e.printStackTrace();
  171. // }
  172. //
  173. // }
  174. // sleep(CHECK_PERIOD);
  175. }
  176. private void sleep(long sleepTime) {
  177. try {
  178. Thread.sleep(sleepTime);
  179. } catch (InterruptedException e) {
  180. e.printStackTrace();
  181. }
  182. }
  183. /**
  184. * 销毁socket
  185. */
  186. public void onDestory() {
  187. if (mClientSocket != null) {
  188. try {
  189. mClientSocket.close();
  190. recvMsg(1);
  191. } catch (IOException e) {
  192. e.printStackTrace();
  193. }
  194. mClientSocket = null;
  195. }
  196. }
  197. /**
  198. * 发送
  199. * @param message
  200. */
  201. public void sendMsg(String message) {
  202. PrintWriter writer;
  203. try {
  204. if (mClientSocket.getOutputStream()==null){
  205. return;
  206. }
  207. writer = new PrintWriter(new OutputStreamWriter(
  208. mClientSocket.getOutputStream()), true);
  209. writer.println(message);
  210. } catch (IOException e) {
  211. // TODO Auto-generated catch block
  212. e.printStackTrace();
  213. }
  214. }
  215. /*
  216. * Ready for use.
  217. */
  218. public void close() {
  219. try {
  220. if (mClientSocket != null && !mClientSocket.isClosed())
  221. mClientSocket.close();
  222. } catch (IOException e) {
  223. // TODO Auto-generated catch block
  224. e.printStackTrace();
  225. }
  226. }
  227. /**
  228. * 处理服务器返回过来的消息
  229. * @param data
  230. */
  231. private void handlerMsg(String data){
  232. //对数据进行protobuf解析
  233. //消息类型:1=登录成功、2=心跳检测、3=推送消息
  234. int msgType=3;
  235. switch(msgType){
  236. case 1:
  237. sendMsg("success");
  238. break;
  239. case 2:
  240. sendMsg("error");
  241. break;
  242. case 3: //需要通知service
  243. // sendMsg("success");
  244. mHandler.obtainMessage(1, data).sendToTarget();
  245. break;
  246. }
  247. }
  248. }