├── .gitignore
├── .idea
├── compiler.xml
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── gradle.xml
├── inspectionProfiles
│ ├── Project_Default.xml
│ └── profiles_settings.xml
├── misc.xml
├── modules.xml
├── runConfigurations.xml
└── vcs.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── tjstudy
│ │ └── tcpclientdemo
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── tjstudy
│ │ │ └── tcpclientdemo
│ │ │ ├── MainActivity.java
│ │ │ ├── MyRecParse.java
│ │ │ ├── RecData.java
│ │ │ ├── adapter
│ │ │ └── ChatAdapter.java
│ │ │ └── bean
│ │ │ └── ChatMess.java
│ └── res
│ │ ├── drawable
│ │ └── shape_chat.xml
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ └── item_rv_chat.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── tjstudy
│ └── tcpclientdemo
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── tcplib
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
└── main
├── AndroidManifest.xml
├── java
└── com
│ └── tjstudy
│ └── tcplib
│ ├── AbsBaseCallback.java
│ ├── BaseRecParse.java
│ ├── RequestCallback.java
│ ├── ResponseCallback.java
│ ├── TCPClient.java
│ ├── TCPClientManager.java
│ └── utils
│ ├── DigitalUtils.java
│ └── LoopBuffer.java
└── res
└── values
└── strings.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | TCPClient
2 | ---------
3 |
4 | [](https://jitpack.io/#WhatWeCan/TCPClient)
5 |
6 | ----------
7 | TCPClient android端的TCP封装
8 |
9 | > 最近手上的一个项目,使用TCP进行数据的访问,根据目前的学习状态做一个简单的封装。
10 | > github地址:https://github.com/WhatWeCan/TCPClient
11 |
12 | 怎么使用?
13 | -----
14 |
15 | 1、导入
16 | ----
17 |
18 | **Step 1**. Add the JitPack repository to your build file
19 | Add it in your root build.gradle at the end of repositories:
20 |
21 | ```
22 | allprojects {
23 | repositories {
24 | ...
25 | maven { url 'https://jitpack.io' }
26 | }
27 | }
28 | ```
29 | **Step 2**. Add the dependency
30 |
31 | ```
32 | dependencies {
33 | compile 'com.github.WhatWeCan:TCPClient:v1.0.2'
34 | }
35 |
36 | ```
37 |
38 | 2、使用方法
39 | ------
40 |
41 | 接收数据
42 | ----
43 |
44 | 接收数据:判断连接是否存在;连接存在 则不进行操作(默认连接存在就一直接收数据),连接不存在,尝试进行重连操作,连接成功接收数据
45 |
46 | **1、自定义接收数据处理方式**
47 |
48 | 自定义接收数据类型
49 |
50 | ```
51 | /**
52 | * 接收数据的类型
53 | */
54 |
55 | public class RecData {
56 | private byte[] head;
57 | private short len;
58 | private byte[] data;
59 |
60 | public RecData() {
61 | }
62 |
63 | public RecData(byte[] head, short len, byte[] data) {
64 | this.head = head;
65 | this.len = len;
66 | this.data = data;
67 | }
68 | //省略 getter setter
69 | }
70 | ```
71 |
72 | 自定义接收数据规则 示例
73 | ```
74 | /**
75 | * 自定义转换规则
76 | * 自定义接收数据的协议
77 | * 示例:接收到的数据必须以$$(2个字节)开头 数据的大小(short,byte 2个字节 数据大小=2+2+数据大小)
78 | */
79 |
80 | public class MyRecParse extends BaseRecParse {
81 | private static final String TAG = "MyRecParse";
82 |
83 | @Override
84 | public List parse() {
85 | ArrayList recDataList = new ArrayList<>();
86 | byte[] baseData = getBaseData();//总数据
87 |
88 | int removeSize = 0;
89 | byte[] head = new byte[2];
90 |
91 | for (int i = 0; i < baseData.length - 1; i++) {
92 | if (baseData[i] == '$' && baseData[i + 1] == '$') {
93 | //找到头了 进一步进行处理
94 | //然后两个字节是数据长度
95 | short dataLen = DigitalUtils.byte2Short(baseData, i + 2);
96 | if (baseData.length - i + 1 > dataLen) {//说明数据完整
97 | Log.e(TAG, "parse: 有完整的数据");
98 | byte[] recData = new byte[dataLen];
99 | System.arraycopy(baseData, i, recData, 0, dataLen);
100 | i += dataLen - 1;
101 | removeSize += dataLen;
102 |
103 | //头
104 | head[0] = baseData[i];
105 | head[1] = baseData[i + 1];
106 | //长度 dataLen
107 | //数据 bytes
108 | recDataList.add(new RecData(head, dataLen, recData));
109 | } else {
110 | Log.e(TAG, "parse: nonono完整的数据");
111 | break;//如果长度不足 就等着
112 | }
113 | } else {
114 | removeSize++;
115 | }
116 | }
117 | notifyLeftData(removeSize);
118 | return recDataList;
119 | }
120 | }
121 | ```
122 | **2、开启接收数据**
123 |
124 | ```
125 | TCPClient.build()
126 | .server(ipAddress, 8888)
127 | .breath("heart".getBytes(), 6 * 1000)
128 | .connTimeout(10 * 1000)
129 | .onResponse(responseCallback);
130 | ```
131 |
132 | 发送数据
133 | ----
134 | 发送数据:判断连接是否存在;连接存在 则直接发送数据,连接不存在,尝试进行重连操作,连接成功发送数据,并接收数据。
135 |
136 | ```
137 | TCPClient.build()
138 | .server(ipAddress, 8888)
139 | .breath("heart".getBytes(), 6 * 1000)
140 | .connTimeout(10 * 1000)
141 | .request(sendMess.getBytes(), 8000, new RequestCallback() {
142 | @Override
143 | public void onTimeout() {
144 | Log.e(TAG, "onTimeout:请求超时,稍后重试 ,关闭连接 ");
145 | TCPClient.closeTcp(ipAddress, 8888);
146 | }
147 |
148 | @Override
149 | public void onFail(Throwable throwable) {
150 | handlerError(throwable);
151 | }
152 | }, responseCallback);//接收数据回调
153 | ```
154 | 关闭连接
155 | ----
156 |
157 | 关闭指定连接
158 | TCPClient.closeTcp(“192.168.5.75”, 8888);
159 |
160 | 简易聊天demo 演示
161 | -------
162 |
163 | 
164 |
165 | 服务器端截图:略
166 |
167 | demo地址
168 | ------
169 |
170 | app:https://github.com/WhatWeCan/TCPClient
171 | server:https://github.com/WhatWeCan/TCPServerDemo
172 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 24
5 | buildToolsVersion "24.0.2"
6 | defaultConfig {
7 | applicationId "com.tjstudy.tcpclientdemo"
8 | minSdkVersion 14
9 | targetSdkVersion 24
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
25 | exclude group: 'com.android.support', module: 'support-annotations'
26 | })
27 | compile 'com.android.support:appcompat-v7:24.2.1'
28 | compile 'com.android.support:design:24.2.1'
29 | testCompile 'junit:junit:4.12'
30 | compile project(path: ':tcplib')
31 | }
32 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/tjstudy/tcpclientdemo/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcpclientdemo;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.tjstudy.tcpclientdemo", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
15 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tjstudy/tcpclientdemo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcpclientdemo;
2 |
3 | import android.os.Bundle;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.support.v7.widget.LinearLayoutManager;
6 | import android.support.v7.widget.RecyclerView;
7 | import android.util.Log;
8 | import android.view.View;
9 | import android.widget.Button;
10 | import android.widget.EditText;
11 |
12 | import com.tjstudy.tcpclientdemo.adapter.ChatAdapter;
13 | import com.tjstudy.tcpclientdemo.bean.ChatMess;
14 | import com.tjstudy.tcplib.RequestCallback;
15 | import com.tjstudy.tcplib.ResponseCallback;
16 | import com.tjstudy.tcplib.TCPClient;
17 |
18 | import java.util.ArrayList;
19 | import java.util.List;
20 |
21 | public class MainActivity extends AppCompatActivity {
22 | private static final String TAG = "MainActivity";
23 | private String ipAddress;
24 | private RecyclerView rvChat;
25 | private ChatAdapter chatAdapter;
26 | private EditText etInput;
27 | private Button btnSend;
28 | private TCPClient tcpClient;
29 | private ArrayList chatMessList;
30 | private LinearLayoutManager chatLayoutManager;
31 |
32 | @Override
33 | protected void onCreate(Bundle savedInstanceState) {
34 | super.onCreate(savedInstanceState);
35 | setContentView(R.layout.activity_main);
36 | ipAddress = "192.168.5.69";
37 | initNet();
38 | initView();
39 | }
40 |
41 | private void initNet() {
42 | tcpClient = TCPClient.build()
43 | .server(ipAddress, 8888)
44 | .breath("heart".getBytes(), 6 * 1000)
45 | .connTimeout(10 * 1000);
46 | }
47 |
48 | private void initView() {
49 | rvChat = (RecyclerView) findViewById(R.id.recycler_chat);
50 | chatLayoutManager = new LinearLayoutManager(this);
51 | rvChat.setLayoutManager(chatLayoutManager);
52 | chatMessList = new ArrayList<>();
53 | chatAdapter = new ChatAdapter(this, chatMessList);
54 | rvChat.setAdapter(chatAdapter);
55 |
56 | etInput = (EditText) findViewById(R.id.et_input);
57 | btnSend = (Button) findViewById(R.id.btn_send);
58 | btnSend.setOnClickListener(new View.OnClickListener() {
59 | @Override
60 | public void onClick(View v) {
61 | final String sendMess = etInput.getText().toString();
62 | ChatMess chatMess = new ChatMess();
63 | chatMess.setType(2);
64 | chatMess.setMesg(sendMess);
65 | chatMessList.add(chatMess);
66 | chatAdapter.notifyDataSetChanged();
67 | chatLayoutManager.scrollToPosition(chatMessList.size() - 1);
68 |
69 | tcpClient.request(sendMess.getBytes(), 8000, new RequestCallback() {
70 | @Override
71 | public void onTimeout() {
72 | Log.e(TAG, "onTimeout:请求超时,稍后重试 ,关闭连接 ");
73 | TCPClient.closeTcp(ipAddress, 8888);
74 | }
75 |
76 | @Override
77 | public void onFail(Throwable throwable) {
78 | handlerError(throwable);
79 | }
80 | }, responseCallback);
81 | }
82 | });
83 | }
84 |
85 | private void handlerError(Throwable throwable) {
86 | Log.e(TAG, "handlerError: 网络访问失败:" + throwable.getMessage());
87 | }
88 |
89 | @Override
90 | protected void onDestroy() {
91 | super.onDestroy();
92 | TCPClient.closeTcp(ipAddress, 8888);
93 | }
94 |
95 | private ResponseCallback responseCallback = new ResponseCallback() {
96 | @Override
97 | public void onRec() {
98 | MyRecParse myRecParse = new MyRecParse();
99 | List dataList = myRecParse.parse();
100 | if (dataList.size() > 0) {
101 | for (RecData recData :
102 | dataList) {
103 | ChatMess chatMess = new ChatMess();
104 | chatMess.setType(1);
105 | chatMess.setMesg(new String(recData.getData()));
106 | chatMessList.add(chatMess);
107 | chatAdapter.notifyDataSetChanged();
108 | chatLayoutManager.scrollToPosition(chatMessList.size() - 1);
109 | }
110 | }
111 | }
112 |
113 | @Override
114 | public void onFail(Throwable throwable) {
115 | handlerError(throwable);
116 | }
117 | };
118 |
119 | /**
120 | * 测试场景:不请求数据时,进行数据的接收 心跳时间间隔改短 6s
121 | *
122 | * @param view
123 | */
124 | public void onRecHeartTest(View view) {
125 | tcpClient.onResponse(responseCallback);
126 | }
127 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/tjstudy/tcpclientdemo/MyRecParse.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcpclientdemo;
2 |
3 | import android.util.Log;
4 |
5 | import com.tjstudy.tcplib.BaseRecParse;
6 | import com.tjstudy.tcplib.utils.DigitalUtils;
7 |
8 | import java.util.ArrayList;
9 | import java.util.List;
10 |
11 | /**
12 | * 自定义转换规则
13 | * 自定义接收数据的协议
14 | * 示例:接收到的数据必须以$$(2个字节)开头 数据的大小(short,byte 2个字节 数据大小=2+2+数据大小)
15 | */
16 |
17 | public class MyRecParse extends BaseRecParse {
18 | private static final String TAG = "MyRecdataFilter";
19 |
20 | @Override
21 | public List parse() {
22 | ArrayList recDataList = new ArrayList<>();
23 | byte[] baseData = getBaseData();//总数据
24 |
25 | int removeSize = 0;
26 | byte[] head = new byte[2];
27 |
28 | for (int i = 0; i < baseData.length - 1; i++) {
29 | if (baseData[i] == '$' && baseData[i + 1] == '$') {
30 | //找到头了 进一步进行处理
31 | //然后两个字节是数据长度
32 | short dataLen = DigitalUtils.byte2Short(baseData, i + 2);
33 | if (baseData.length - i + 1 > dataLen) {//说明数据完整
34 | byte[] recData = new byte[dataLen];
35 | System.arraycopy(baseData, i + 4, recData, 0, dataLen - 4);
36 | Log.e(TAG, "parse: 有完整的数据=" + new String(recData));
37 | i += dataLen - 1;
38 | removeSize += dataLen;
39 |
40 | //头
41 | head[0] = recData[0];
42 | head[1] = recData[1];
43 | //长度 dataLen
44 | //数据 bytes
45 | recDataList.add(new RecData(head, dataLen, recData));
46 | } else {
47 | Log.e(TAG, "parse: nonono完整的数据");
48 | break;//如果长度不足 就等着
49 | }
50 | } else {
51 | removeSize++;
52 | }
53 | }
54 | notifyLeftData(removeSize);
55 | return recDataList;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tjstudy/tcpclientdemo/RecData.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcpclientdemo;
2 |
3 | /**
4 | * 接收数据的类型
5 | */
6 |
7 | public class RecData {
8 | private byte[] head;
9 | private short len;
10 | private byte[] data;
11 |
12 | public RecData() {
13 | }
14 |
15 | public RecData(byte[] head, short len, byte[] data) {
16 | this.head = head;
17 | this.len = len;
18 | this.data = data;
19 | }
20 |
21 | public byte[] getHead() {
22 | return head;
23 | }
24 |
25 | public void setHead(byte[] head) {
26 | this.head = head;
27 | }
28 |
29 | public short getLen() {
30 | return len;
31 | }
32 |
33 | public void setLen(short len) {
34 | this.len = len;
35 | }
36 |
37 | public byte[] getData() {
38 | return data;
39 | }
40 |
41 | public void setData(byte[] data) {
42 | this.data = data;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tjstudy/tcpclientdemo/adapter/ChatAdapter.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcpclientdemo.adapter;
2 |
3 | import android.content.Context;
4 | import android.support.v7.widget.RecyclerView;
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 | import android.widget.TextView;
9 |
10 | import com.tjstudy.tcpclientdemo.R;
11 | import com.tjstudy.tcpclientdemo.bean.ChatMess;
12 |
13 | import java.util.List;
14 |
15 | /**
16 | * Chat adapter
17 | */
18 |
19 | public class ChatAdapter extends RecyclerView.Adapter {
20 | List chatMessList;
21 | Context mContext;
22 |
23 | public ChatAdapter(Context mContext, List chatMessList) {
24 | this.chatMessList = chatMessList;
25 | this.mContext = mContext;
26 | }
27 |
28 | @Override
29 | public ChatHolder onCreateViewHolder(ViewGroup parent, int viewType) {
30 | return new ChatHolder(LayoutInflater.from(mContext).inflate(R.layout.item_rv_chat, parent, false));
31 | }
32 |
33 | @Override
34 | public void onBindViewHolder(ChatHolder holder, int position) {
35 | ChatMess chatMess = chatMessList.get(position);
36 | if (chatMess.getType() == 1) {
37 | holder.tvSend.setVisibility(View.GONE);
38 | holder.tvRec.setVisibility(View.VISIBLE);
39 | holder.tvRec.setText(chatMess.getMesg());
40 | } else {
41 | holder.tvRec.setVisibility(View.GONE);
42 | holder.tvSend.setVisibility(View.VISIBLE);
43 | holder.tvSend.setText(chatMess.getMesg());
44 | }
45 | }
46 |
47 | @Override
48 | public int getItemCount() {
49 | return chatMessList.size();
50 | }
51 |
52 | public class ChatHolder extends RecyclerView.ViewHolder {
53 |
54 | TextView tvSend;
55 | TextView tvRec;
56 |
57 | public ChatHolder(View itemView) {
58 | super(itemView);
59 | tvSend = (TextView) itemView.findViewById(R.id.tv_send);
60 | tvRec = (TextView) itemView.findViewById(R.id.tv_rec);
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tjstudy/tcpclientdemo/bean/ChatMess.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcpclientdemo.bean;
2 |
3 | /**
4 | * 聊天 消息实体
5 | */
6 |
7 | public class ChatMess {
8 | private int type;
9 | private String mesg;
10 |
11 | public int getType() {
12 | return type;
13 | }
14 |
15 | public void setType(int type) {
16 | this.type = type;
17 | }
18 |
19 | public String getMesg() {
20 | return mesg;
21 | }
22 |
23 | public void setMesg(String mesg) {
24 | this.mesg = mesg;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/shape_chat.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
11 |
12 |
17 |
18 |
23 |
24 |
33 |
34 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_rv_chat.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
17 |
18 |
28 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WhatWeCan/TCPClient/eb22f5fb38c7ded3e67524a7d3b54816f0070bfc/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WhatWeCan/TCPClient/eb22f5fb38c7ded3e67524a7d3b54816f0070bfc/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WhatWeCan/TCPClient/eb22f5fb38c7ded3e67524a7d3b54816f0070bfc/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WhatWeCan/TCPClient/eb22f5fb38c7ded3e67524a7d3b54816f0070bfc/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WhatWeCan/TCPClient/eb22f5fb38c7ded3e67524a7d3b54816f0070bfc/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | TCPClientDemo
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/tjstudy/tcpclientdemo/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcpclientdemo;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.2.0'
9 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
10 |
11 | // NOTE: Do not place your application dependencies here; they belong
12 | // in the individual module build.gradle files
13 | }
14 | }
15 |
16 | allprojects {
17 | repositories {
18 | jcenter()
19 | }
20 | }
21 |
22 | task clean(type: Delete) {
23 | delete rootProject.buildDir
24 | }
25 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WhatWeCan/TCPClient/eb22f5fb38c7ded3e67524a7d3b54816f0070bfc/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':tcplib'
2 |
--------------------------------------------------------------------------------
/tcplib/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/tcplib/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 | group='com.github.WhatWeCan'
4 |
5 | android {
6 | compileSdkVersion 22
7 | buildToolsVersion "22.0.1"
8 |
9 | defaultConfig {
10 | minSdkVersion 9
11 | targetSdkVersion 22
12 | versionCode 1
13 | versionName "1.0"
14 | }
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | }
22 |
23 | dependencies {
24 | compile fileTree(dir: 'libs', include: ['*.jar'])
25 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
26 | exclude group: 'com.android.support', module: 'support-annotations'
27 | })
28 | compile 'com.android.support:appcompat-v7:22.+'
29 | }
30 |
--------------------------------------------------------------------------------
/tcplib/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/tcplib/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/tcplib/src/main/java/com/tjstudy/tcplib/AbsBaseCallback.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcplib;
2 |
3 | public interface AbsBaseCallback {
4 | void onFail(Throwable throwable);
5 | }
--------------------------------------------------------------------------------
/tcplib/src/main/java/com/tjstudy/tcplib/BaseRecParse.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcplib;
2 |
3 | import com.tjstudy.tcplib.utils.LoopBuffer;
4 |
5 | import java.util.List;
6 |
7 | /**
8 | * 默认接收数据处理方式:不进行处理 直接返回接收到的数据
9 | */
10 | public abstract class BaseRecParse {
11 | private final LoopBuffer instance;
12 | private final byte[] data;
13 |
14 | public BaseRecParse() {
15 | instance = LoopBuffer.getInstance();
16 | data = instance.read(instance.count());
17 | }
18 |
19 | public abstract List parse();
20 |
21 | /**
22 | * 获取接收到的数据
23 | *
24 | * @return
25 | */
26 | public byte[] getBaseData() {
27 | return data;
28 | }
29 |
30 | /**
31 | * 更新剩下的数据
32 | *
33 | * @param outSize 处理数据长度
34 | */
35 | public void notifyLeftData(int outSize) {
36 | instance.remove(outSize);
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/tcplib/src/main/java/com/tjstudy/tcplib/RequestCallback.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcplib;
2 |
3 | /**
4 | * 接收数据callback
5 | */
6 |
7 | public abstract class RequestCallback implements AbsBaseCallback {
8 | public abstract void onTimeout();
9 | }
10 |
--------------------------------------------------------------------------------
/tcplib/src/main/java/com/tjstudy/tcplib/ResponseCallback.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcplib;
2 |
3 | /**
4 | * 读取数据返回接口
5 | */
6 |
7 | public abstract class ResponseCallback implements AbsBaseCallback {
8 | public abstract void onRec();
9 | }
--------------------------------------------------------------------------------
/tcplib/src/main/java/com/tjstudy/tcplib/TCPClient.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcplib;
2 |
3 | import android.os.Handler;
4 | import android.os.Message;
5 |
6 | import com.tjstudy.tcplib.utils.LoopBuffer;
7 |
8 | import java.io.IOException;
9 | import java.io.InputStream;
10 | import java.io.OutputStream;
11 | import java.net.InetSocketAddress;
12 | import java.net.Socket;
13 | import java.net.SocketException;
14 | import java.net.SocketTimeoutException;
15 |
16 | /**
17 | * 设置连接参数
18 | */
19 |
20 | public class TCPClient {
21 | /**
22 | * 服务器ip
23 | */
24 | private String mServerIp;
25 | /**
26 | * 服务器端口号
27 | */
28 | private int mServerPort;
29 | /**
30 | * 连接超时时间 默认设置为10s
31 | */
32 | private int mConnTimeout = 10 * 1000;
33 | /**
34 | * 心跳数据
35 | */
36 | private byte[] mBreath;
37 | /**
38 | * 心跳间隔时间
39 | */
40 | private int mBreathTime;
41 | private static TCPClient client;
42 | private int readTimeout;
43 | private RequestCallback requestCallback;
44 | private byte[] sendData;
45 | private long sendTime;
46 | private long recTime;
47 | private ResponseCallback responseCallback;
48 |
49 | private TCPClient() {
50 | }
51 |
52 | /**
53 | * 获取TCPClient的实例
54 | *
55 | * @return
56 | */
57 | public static TCPClient build() {
58 | if (client == null) {
59 | synchronized (TCPClient.class) {
60 | if (client == null) {
61 | client = new TCPClient();
62 | }
63 | }
64 | }
65 | return client;
66 | }
67 |
68 | private static final int SOCKET_OK = 10003;
69 | private static final int SOCKET_CLOSED = 10004;
70 | private static final int RE_CONN_SUCCESS = 10005;
71 | private static final int RE_CONN_FAIL = 10006;
72 | private static final int ON_RECEIVE_DATA = 10007;
73 | private static final int ON_REQUEST_FAIL = 10008;
74 | private static final int ON_RECEIVE_DATA_TIMEOUT = 10009;
75 | private Handler mHandler = new Handler() {
76 | @Override
77 | public void handleMessage(Message msg) {
78 | switch (msg.what) {
79 | case SOCKET_OK:
80 | //发送数据
81 | Socket socket = (Socket) msg.obj;
82 | request(socket);
83 | break;
84 | case SOCKET_CLOSED:
85 | //尝试进行重新连接
86 | connectServerInner();
87 | break;
88 | case RE_CONN_SUCCESS:
89 | //发送数据
90 | socket = (Socket) msg.obj;
91 | request(socket);
92 | receive(socket);
93 | sendBreadth(socket);
94 | break;
95 | case ON_RECEIVE_DATA:
96 | if (responseCallback != null) {
97 | responseCallback.onRec();
98 | }
99 | break;
100 | case RE_CONN_FAIL:
101 | Throwable connE = (Throwable) msg.obj;
102 | throwBack(connE);
103 | break;
104 | case ON_REQUEST_FAIL:
105 | Throwable requestE = (Throwable) msg.obj;
106 | throwBack(requestE);
107 | break;
108 |
109 | case ON_RECEIVE_DATA_TIMEOUT:
110 | if (requestCallback != null) {
111 | requestCallback.onTimeout();
112 | }
113 | break;
114 | }
115 | }
116 | };
117 |
118 | /**
119 | * 设置目标服务器的ip和端口号
120 | *
121 | * @param ip ip地址
122 | * @param port 端口号
123 | * @return
124 | */
125 | public TCPClient server(String ip, int port) {
126 | mServerIp = ip;
127 | mServerPort = port;
128 | return this;
129 | }
130 |
131 | /**
132 | * 设置连接超时时间
133 | *
134 | * @param connTimeout 连接超时时间
135 | * @return
136 | */
137 | public TCPClient connTimeout(int connTimeout) {
138 | mConnTimeout = connTimeout;
139 | return this;
140 | }
141 |
142 | /**
143 | * 设置心跳数据
144 | *
145 | * @param breath 心跳内容
146 | * @param breathTime 心跳间隔时间
147 | * @return
148 | */
149 | public TCPClient breath(byte[] breath, int breathTime) {
150 | mBreath = breath;
151 | mBreathTime = breathTime;
152 | return this;
153 | }
154 |
155 | //----------------------发送数据:判断连接是否存在;连接存在 则直接发送数据,连接不存在,尝试进行连接,连接成功发送数据
156 |
157 | /**
158 | * 发送请求到服务器
159 | *
160 | * @param data 数据
161 | * @param timeout 请求响应超时时间
162 | * @param request 请求状态
163 | * @param response 接收数据
164 | */
165 | public synchronized void request(byte[] data, int timeout, RequestCallback request, ResponseCallback response) {
166 | readTimeout = timeout;
167 | requestCallback = request;
168 | responseCallback = response;
169 | sendData = data;
170 | isServerOpen();
171 | }
172 | //----------------------接收数据:判断连接是否存在;连接存在 则不进行操作,连接不存在,尝试进行连接,连接成功接收数据
173 |
174 | /**
175 | * 接收数据
176 | *
177 | * @param responseCallBack 接收数据
178 | */
179 | public void onResponse(ResponseCallback responseCallBack) {
180 | this.responseCallback = responseCallBack;
181 | isServerOpen();
182 | }
183 |
184 | /**
185 | * 关闭指定连接
186 | *
187 | * @param ip
188 | * @param port
189 | */
190 | public static void closeTcp(final String ip, final int port) {
191 | new Thread(new Runnable() {
192 | @Override
193 | public void run() {
194 | Socket socket = TCPClientManager.queryTarget(ip, port);
195 | if (socket != null) {
196 | TCPClientManager.removeTcp(socket);
197 | }
198 | }
199 | }).start();
200 | }
201 |
202 | /**
203 | * 关闭当前连接
204 | */
205 | public void closeTcp() {
206 | new Thread(new Runnable() {
207 | @Override
208 | public void run() {
209 | Socket socket = TCPClientManager.queryTarget(mServerIp, mServerPort);
210 | if (socket != null) {
211 | TCPClientManager.removeTcp(socket);
212 | }
213 | }
214 | }).start();
215 | }
216 |
217 | /**
218 | * 开启线程连接服务器
219 | */
220 | private void connectServerInner() {
221 | new Thread(new Runnable() {
222 | @Override
223 | public void run() {
224 | try {
225 | Socket socket = new Socket();
226 | socket.setSoTimeout(10 * 1000);//设置读取超时时间
227 | socket.connect(new InetSocketAddress(mServerIp, mServerPort), mConnTimeout);
228 | //连接服务器成功
229 | TCPClientManager.addTCP(socket);//添加到列表
230 | Message message = mHandler.obtainMessage();
231 | message.what = RE_CONN_SUCCESS;
232 | message.obj = socket;
233 | mHandler.sendMessage(message);
234 | } catch (final IOException e) {
235 | e.printStackTrace();
236 | Message message = mHandler.obtainMessage();
237 | message.what = RE_CONN_FAIL;
238 | message.obj = e;
239 | mHandler.sendMessage(message);
240 |
241 | }
242 | }
243 | }).start();
244 | }
245 |
246 | /**
247 | * 内部处理:发送心跳
248 | */
249 | private void sendBreadth(final Socket socket) {
250 | if (mBreath == null) {
251 | return;
252 | }
253 | new Thread(new Runnable() {
254 | @Override
255 | public void run() {
256 | while (socket != null && !socket.isClosed()) {
257 | try {
258 | OutputStream os = socket.getOutputStream();
259 | os.write(mBreath);//发送心跳
260 | os.flush();
261 | Thread.sleep(mBreathTime);
262 | } catch (IOException | InterruptedException e) {
263 | e.printStackTrace();
264 | if (socket.isClosed()) {
265 | break;
266 | }
267 | }
268 | }
269 | }
270 | }).start();
271 | }
272 |
273 | /**
274 | * 内部处理:发送请求
275 | *
276 | * @param socket
277 | */
278 | private synchronized void request(final Socket socket) {
279 | new Thread(new Runnable() {
280 | @Override
281 | public void run() {
282 | try {
283 | OutputStream os = socket.getOutputStream();
284 | if (sendData != null) {
285 | os.write(sendData);//发送请求
286 | os.flush();
287 | }
288 | } catch (final IOException e) {
289 | e.printStackTrace();
290 | Message message = mHandler.obtainMessage();
291 | message.what = ON_REQUEST_FAIL;
292 | message.obj = e;
293 | mHandler.sendMessage(message);
294 | }
295 | }
296 | }).start();
297 | sendTime = System.currentTimeMillis();
298 | if (readTimeout != 0) {
299 | mHandler.postDelayed(new Runnable() {
300 | @Override
301 | public void run() {
302 | if (recTime < sendTime) {
303 | mHandler.sendEmptyMessage(ON_RECEIVE_DATA_TIMEOUT);
304 | }
305 | }
306 | }, readTimeout + 1000);
307 | }
308 | }
309 |
310 | /**
311 | * 内部处理:接收数据
312 | *
313 | * @param socket
314 | */
315 | private void receive(final Socket socket) {
316 | new Thread(new Runnable() {
317 | @Override
318 | public void run() {
319 | while (socket.isConnected() && !socket.isClosed()) {
320 | //接收socket数据
321 | try {
322 | InputStream is = socket.getInputStream();
323 | byte[] data = new byte[1024];
324 | int len = is.read(data);
325 | byte[] newData = new byte[len];
326 | System.arraycopy(data, 0, newData, 0, len);
327 | LoopBuffer.getInstance().write(newData);
328 | recTime = System.currentTimeMillis();
329 | mHandler.sendEmptyMessage(ON_RECEIVE_DATA);
330 | } catch (SocketTimeoutException ignored) {
331 | } catch (SocketException e) {
332 | if (socket.isClosed()) {
333 | break;
334 | }
335 | } catch (IOException e) {
336 | e.printStackTrace();
337 | }
338 | }
339 | }
340 | }).start();
341 | }
342 |
343 | /**
344 | * 判断网络是否打开的操作
345 | */
346 | private void isServerOpen() {
347 | new Thread(new Runnable() {
348 | @Override
349 | public void run() {
350 | //查看指定服务器是否已经连接
351 | Socket socket = TCPClientManager.queryTarget(mServerIp, mServerPort);
352 | if (socket != null) {
353 | Message message = mHandler.obtainMessage();
354 | message.what = SOCKET_OK;
355 | message.obj = socket;
356 | mHandler.sendMessage(message);
357 | } else {
358 | Message message = mHandler.obtainMessage();
359 | message.what = SOCKET_CLOSED;
360 | mHandler.sendMessage(message);
361 | }
362 | }
363 | }).start();
364 | }
365 |
366 | private void throwBack(Throwable e) {
367 | if (responseCallback != null) {
368 | responseCallback.onFail(e);
369 | }
370 | if (requestCallback != null) {
371 | requestCallback.onFail(e);
372 | }
373 | }
374 | }
375 |
--------------------------------------------------------------------------------
/tcplib/src/main/java/com/tjstudy/tcplib/TCPClientManager.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcplib;
2 |
3 | import java.io.IOException;
4 | import java.net.InetAddress;
5 | import java.net.Socket;
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | /**
10 | * TCPClient 管理类
11 | */
12 |
13 | public class TCPClientManager {
14 | private static List managerList = new ArrayList<>();
15 |
16 | /**
17 | * 添加socket 到列表
18 | *
19 | * @param socket
20 | */
21 | public static void addTCP(Socket socket) {
22 | managerList.add(socket);
23 | }
24 |
25 | /**
26 | * 从列表移除socket
27 | *
28 | * @param socket
29 | */
30 | public static void removeTcp(Socket socket) {
31 | if (socket != null) {
32 | try {
33 | socket.close();
34 | } catch (IOException e) {
35 | e.printStackTrace();
36 | } finally {
37 | managerList.remove(socket);
38 | }
39 | }
40 | }
41 |
42 | /**
43 | * 查询指定ip地址的服务器是否在列表中
44 | *
45 | * @param ip
46 | * @param port
47 | * @return
48 | */
49 | public static Socket queryTarget(String ip, int port) {
50 | if (managerList.size() > 0) {
51 | for (Socket inner :
52 | managerList) {
53 | InetAddress inetAddress = inner.getInetAddress();
54 | if (inetAddress != null
55 | && inetAddress.getHostName().equals(ip)
56 | && inner.getPort() == port) {
57 | return inner;
58 | }
59 | }
60 | }
61 | return null;
62 | }
63 |
64 | public static void closeAll() {
65 | if (managerList.size() > 0) {
66 | for (Socket inner :
67 | managerList) {
68 | removeTcp(inner);
69 | }
70 | }
71 | managerList.clear();
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/tcplib/src/main/java/com/tjstudy/tcplib/utils/DigitalUtils.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcplib.utils;
2 |
3 | import java.io.UnsupportedEncodingException;
4 | import java.nio.ByteBuffer;
5 | import java.nio.CharBuffer;
6 | import java.nio.charset.Charset;
7 |
8 | /**
9 | * 数字工具
10 | *
11 | * @author Administrator
12 | */
13 | public class DigitalUtils {
14 |
15 | /**
16 | * 将字符串转换为byte数组
17 | *
18 | * @param str
19 | * @param length
20 | * @return
21 | */
22 | public static void packMessageString(String str, int length, byte[] buff, int[] start) {
23 | try {
24 | byte[] strByte = str.getBytes("GBK");
25 | int realLen = strByte.length;
26 | if (realLen > length)
27 | realLen = length;
28 | System.arraycopy(strByte, 0, buff, start[0], realLen);
29 | start[0] += length;
30 | } catch (UnsupportedEncodingException e) {
31 | e.printStackTrace();
32 | }
33 | }
34 |
35 | public static void packMessageInt(int data, byte[] buff, int[] start) {
36 | byte[] d = int2Byte(data);
37 | System.arraycopy(d, 0, buff, start[0], 4);
38 | start[0] += 4;
39 | }
40 |
41 | public static void packMessageShort(short data, byte[] buff, int[] start) {
42 | byte[] d = short2Byte(data);
43 | System.arraycopy(d, 0, buff, start[0], 2);
44 | start[0] += 2;
45 | }
46 |
47 | public static void packMessageByte(byte data, byte[] buff, int[] start) {
48 | buff[start[0]] = data;
49 | start[0] += 1;
50 | }
51 |
52 | public static String parseMessageString(byte[] buf, int[] start, int count) {
53 | byte[] result = new byte[count];
54 | System.arraycopy(buf, start[0], result, 0, count);
55 | start[0] += count;
56 | return byte2String(result).trim();
57 | }
58 |
59 | public static int parseMessageInt(byte[] buf, int[] start) {
60 | if(buf.length<4){
61 | return -1;
62 | }
63 |
64 | byte[] result = new byte[4];
65 | System.arraycopy(buf, start[0], result, 0, 4);
66 | start[0] += 4;
67 |
68 | String s = "";
69 | for (byte b :
70 | result) {
71 | s += b + ",";
72 | }
73 | return byte2Int(result);
74 | }
75 |
76 | public static int parseMessageShort(byte[] buf, int[] start) {
77 | if(buf.length<2){
78 | return -1;
79 | }
80 | byte[] result = new byte[2];
81 | System.arraycopy(buf, start[0], result, 0, 2);
82 | start[0] += 2;
83 | return byte2Short(result);
84 | }
85 |
86 | public static byte parseMessageByte(byte[] buf, int[] start) {
87 | byte b = buf[start[0]];
88 | start[0] += 1;
89 | return b;
90 | }
91 |
92 | /**
93 | * 将长度为4的byte数组转换为16位int
94 | * 大端字序
95 | *
96 | * @param res byte[]
97 | * @return int
98 | */
99 | private static int byte2Int(byte[] res) {
100 | return (res[0] & 0xff) | ((res[1] << 8) & 0xff00)
101 | | ((res[2] << 16) & 0xff0000) | ((res[3] << 24) & 0xff000000); // 表示安位或
102 | }
103 |
104 | /**
105 | * 将int 转为四个字节的byte
106 | *
107 | * @param i
108 | * @return
109 | */
110 | private static byte[] int2Byte(int i) {
111 | byte[] result = new byte[4];
112 | result[0] = (byte) (i & 0xFF);
113 | result[1] = (byte) ((i >> 8) & 0xFF);
114 | result[2] = (byte) ((i >> 16) & 0xFF);
115 | result[3] = (byte) ((i >> 24) & 0xFF);
116 | return result;
117 | }
118 |
119 | /**
120 | * 将byte数组转换为字符串
121 | *
122 | * @param src
123 | * @return
124 | */
125 | private static String byte2String(byte[] src) {
126 | String gbk = "";
127 | try {
128 | gbk = new String(src, "gbk");
129 | } catch (UnsupportedEncodingException e) {
130 | e.printStackTrace();
131 | }
132 | return gbk;
133 | }
134 |
135 | /**
136 | * 将short转换为byte数组
137 | *
138 | * @param s short
139 | * @return
140 | */
141 | private static byte[] short2Byte(int s) {
142 | byte[] shortBuf = new byte[2];
143 | for (int i = 0; i < 2; i++) {
144 | int offset = (shortBuf.length - 1 - i) * 8;
145 | shortBuf[1 - i] = (byte) ((s >>> offset) & 0xff);
146 | }
147 | return shortBuf;
148 | }
149 |
150 | /**
151 | * 将长度为2的byte数组转换为16位int
152 | *
153 | * @param res byte[]
154 | * @return int
155 | */
156 | private static int byte2Short(byte[] res) {
157 | return (res[0] & 0xff) | ((res[1] << 8) & 0xff00); // | 表示安位或
158 | }
159 |
160 | /**
161 | * 将长度为2的byte数组转换为16位int
162 | *
163 | * @param res byte[]
164 | * @return int
165 | */
166 | public static short byte2Short(byte[] res, int start) {
167 | int targets = (res[start] & 0xff) | ((res[start + 1] << 8) & 0xff00); // | 表示安位或
168 | return (short) targets;
169 | }
170 |
171 | /**
172 | * 根据char数组获取byte数组
173 | *
174 | * @param chars
175 | * @return
176 | */
177 | public static byte[] getBytes(char[] chars) {
178 | Charset cs = Charset.forName("gbk");
179 | CharBuffer cb = CharBuffer.allocate(chars.length);
180 | cb.put(chars);
181 | cb.flip();
182 | ByteBuffer bb = cs.encode(cb);
183 |
184 | return bb.array();
185 | }
186 |
187 | /**
188 | * 根据byte数组获取char数组
189 | *
190 | * @param bytes
191 | * @return
192 | */
193 | public static char[] getChars(byte[] bytes) {
194 | Charset cs = Charset.forName("gbk");
195 | ByteBuffer bb = ByteBuffer.allocate(bytes.length);
196 | bb.put(bytes);
197 | bb.flip();
198 | CharBuffer cb = cs.decode(bb);
199 |
200 | return cb.array();
201 | }
202 |
203 | /**
204 | * @param msg 需要计算校验和的byte数组(无符号校验和)
205 | * @param start msg的开始位置
206 | * @return 计算出的校验和数组
207 | */
208 | public static short sumCheckShort(byte[] msg, int start, int count) {
209 | byte[] newByte = new byte[count];
210 | System.arraycopy(msg, start, newByte, 0, newByte.length);
211 | int mSum = 0;
212 | int temp;
213 | short chksum;
214 | int i = 0;
215 | for (; i < newByte.length - 1; i += 2) {
216 | temp = newByte[i + 1];
217 | temp <<= 8;
218 | if (temp < 0) {
219 | temp += 65536;
220 | }
221 | if (newByte[i] < 0) {
222 | temp += 256;
223 | }
224 | temp += newByte[i];
225 | mSum += temp;
226 | }
227 | if (i != newByte.length) {
228 | if (newByte[newByte.length - 1] < 0) {
229 | mSum += 256;
230 | }
231 | mSum += newByte[newByte.length - 1];
232 | }
233 | mSum = (mSum >> 16) + (mSum & 0xffff);
234 | mSum += (mSum >> 16);
235 | chksum = (short) ~mSum;
236 | return chksum;
237 | }
238 |
239 | /**
240 | * 组合byte数组
241 | *
242 | * @param bs
243 | * @return
244 | */
245 | public static byte[] mergeBytes(byte[]... bs) {
246 | int length = 0;
247 | for (byte[] bs2 : bs) {
248 | length += bs2.length;
249 | }
250 | // 请求数组长度
251 | byte[] result = new byte[length];
252 | int curLength = 0;
253 | for (byte[] b : bs) {
254 | System.arraycopy(b, 0, result, curLength, b.length);
255 | curLength += b.length;
256 | }
257 | return result;
258 | }
259 |
260 | public static String bytesToHexString(byte[] src) {
261 | StringBuilder stringBuilder = new StringBuilder("");
262 | if (src == null || src.length <= 0) {
263 | return null;
264 | }
265 | for (int i = 0; i < src.length; i++) {
266 | int v = src[i] & 0xFF;
267 | String hv = Integer.toHexString(v);
268 | if (hv.length() < 2) {
269 | stringBuilder.append(0);
270 | }
271 | stringBuilder.append(hv + " ");
272 | }
273 | return stringBuilder.toString();
274 | }
275 | }
276 |
--------------------------------------------------------------------------------
/tcplib/src/main/java/com/tjstudy/tcplib/utils/LoopBuffer.java:
--------------------------------------------------------------------------------
1 | package com.tjstudy.tcplib.utils;
2 |
3 | /**
4 | * loopBuffer
5 | */
6 | public class LoopBuffer {
7 | private static int wp = 0;
8 | private static int rp = 0;
9 | private static int count = 0;
10 | private static int maxlen = 0;
11 | private static byte[] buff;
12 | private static LoopBuffer instance;
13 |
14 | private LoopBuffer() {
15 | }
16 |
17 | public static LoopBuffer getInstance() {
18 | if (instance == null) {
19 | synchronized (LoopBuffer.class) {
20 | if (instance == null) {
21 | instance = new LoopBuffer(1024);
22 | }
23 | }
24 | }
25 | return instance;
26 | }
27 |
28 | private LoopBuffer(int len) {
29 | wp = 0;
30 | rp = 0;
31 | count = 0;
32 | maxlen = len;
33 | buff = new byte[maxlen];
34 | }
35 |
36 | public void write(byte[] data) {
37 | if (count + data.length > maxlen)
38 | return;
39 |
40 | int rlen = maxlen - wp;
41 | if (rlen > data.length) {
42 | System.arraycopy(data, 0, buff, wp, data.length);
43 | wp += data.length;
44 | if (wp >= maxlen) {
45 | wp %= maxlen;
46 | }
47 | } else {
48 | System.arraycopy(data, 0, buff, wp, rlen);
49 | System.arraycopy(data, rlen, buff, 0, data.length - rlen);
50 | wp = data.length - rlen;
51 | }
52 | count += data.length;
53 | }
54 |
55 | public byte[] read(int readLen) {
56 | if (readLen > count)
57 | readLen = count;
58 |
59 | byte[] rbuf = new byte[readLen];
60 | int rlen = maxlen - rp;
61 | if (readLen < rlen) {
62 | System.arraycopy(buff, rp, rbuf, 0, readLen);
63 | } else {
64 | int len1 = maxlen - rp;
65 | System.arraycopy(buff, rp, rbuf, 0, len1);
66 | System.arraycopy(buff, 0, rbuf, len1, readLen - len1);
67 | }
68 |
69 | return rbuf;
70 | }
71 |
72 | public int count() {
73 | return count;
74 | }
75 |
76 | public void remove(int len) {
77 | if (len > count)
78 | return;
79 | count -= len;
80 | rp += len;
81 | rp %= maxlen;
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/tcplib/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | TCPLib
3 |
4 |
--------------------------------------------------------------------------------