├── .github
└── workflows
│ └── android.yml
├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── doc
├── allclasses-frame.html
├── allclasses-noframe.html
├── com
│ └── zhangke
│ │ └── websocket
│ │ ├── DefaultReconnectManager.html
│ │ ├── NetworkChangedReceiver.html
│ │ ├── ReconnectManager.OnConnectListener.html
│ │ ├── ReconnectManager.html
│ │ ├── SimpleDispatcher.html
│ │ ├── SimpleListener.html
│ │ ├── SocketListener.html
│ │ ├── SocketWrapperListener.html
│ │ ├── WebSocketEngine.html
│ │ ├── WebSocketHandler.html
│ │ ├── WebSocketManager.html
│ │ ├── WebSocketSetting.html
│ │ ├── WebSocketWrapper.html
│ │ ├── dispatcher
│ │ ├── DefaultResponseDispatcher.html
│ │ ├── EngineThread.html
│ │ ├── IResponseDispatcher.html
│ │ ├── MainThreadResponseDelivery.html
│ │ ├── ResponseDelivery.html
│ │ ├── ResponseProcessEngine.html
│ │ ├── package-frame.html
│ │ ├── package-summary.html
│ │ └── package-tree.html
│ │ ├── package-frame.html
│ │ ├── package-summary.html
│ │ ├── package-tree.html
│ │ ├── request
│ │ ├── ByteArrayRequest.html
│ │ ├── ByteBufferRequest.html
│ │ ├── CollectionFrameDataRequest.html
│ │ ├── FrameDataRequest.html
│ │ ├── PingRequest.html
│ │ ├── PongRequest.html
│ │ ├── Request.html
│ │ ├── RequestFactory.html
│ │ ├── StringRequest.html
│ │ ├── package-frame.html
│ │ ├── package-summary.html
│ │ └── package-tree.html
│ │ ├── response
│ │ ├── ByteBufferResponse.html
│ │ ├── ErrorResponse.html
│ │ ├── PingResponse.html
│ │ ├── PongResponse.html
│ │ ├── Response.html
│ │ ├── ResponseFactory.html
│ │ ├── TextResponse.html
│ │ ├── package-frame.html
│ │ ├── package-summary.html
│ │ └── package-tree.html
│ │ └── util
│ │ ├── LogImpl.html
│ │ ├── LogUtil.html
│ │ ├── Logable.html
│ │ ├── PermissionUtil.html
│ │ ├── ThreadUtil.html
│ │ ├── package-frame.html
│ │ ├── package-summary.html
│ │ └── package-tree.html
├── constant-values.html
├── deprecated-list.html
├── help-doc.html
├── index-files
│ ├── index-1.html
│ ├── index-10.html
│ ├── index-11.html
│ ├── index-12.html
│ ├── index-13.html
│ ├── index-14.html
│ ├── index-15.html
│ ├── index-16.html
│ ├── index-17.html
│ ├── index-18.html
│ ├── index-2.html
│ ├── index-3.html
│ ├── index-4.html
│ ├── index-5.html
│ ├── index-6.html
│ ├── index-7.html
│ ├── index-8.html
│ └── index-9.html
├── index.html
├── overview-frame.html
├── overview-summary.html
├── overview-tree.html
├── package-list
├── script.js
└── stylesheet.css
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── image
├── dispatcher.png
├── qrcode_for_account.jpg
├── qrcode_for_gsubscription.jpg
├── websocketservice.png
└── websocketthread.png
├── samples
├── dispatersample
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src
│ │ └── main
│ │ ├── AndroidManifest.xml
│ │ ├── java
│ │ └── com
│ │ │ └── zhangke
│ │ │ └── smaple
│ │ │ └── dispatersample
│ │ │ ├── App.java
│ │ │ ├── AppResponseDispatcher.java
│ │ │ ├── CommonResponseEntity.java
│ │ │ └── MainActivity.java
│ │ └── res
│ │ ├── drawable
│ │ └── ic_launcher.png
│ │ ├── layout
│ │ └── activity_main.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
└── simple
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── zhangke
│ │ └── websocketdemo
│ │ ├── App.java
│ │ ├── TestActivity.java
│ │ └── UiUtil.java
│ └── res
│ ├── drawable
│ └── ic_launcher.png
│ ├── layout
│ └── activity_test.xml
│ └── values
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
├── settings.gradle
└── websocketlib
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
└── main
├── AndroidManifest.xml
├── java
└── com
│ └── zhangke
│ └── websocket
│ ├── DefaultReconnectManager.java
│ ├── NetworkChangedReceiver.java
│ ├── ReconnectManager.java
│ ├── SimpleDispatcher.java
│ ├── SimpleListener.java
│ ├── SocketListener.java
│ ├── SocketWrapperListener.java
│ ├── WebSocketEngine.java
│ ├── WebSocketHandler.java
│ ├── WebSocketManager.java
│ ├── WebSocketSetting.java
│ ├── WebSocketWrapper.java
│ ├── dispatcher
│ ├── DefaultResponseDispatcher.java
│ ├── EngineThread.java
│ ├── IResponseDispatcher.java
│ ├── MainThreadResponseDelivery.java
│ ├── ResponseDelivery.java
│ └── ResponseProcessEngine.java
│ ├── request
│ ├── ByteArrayRequest.java
│ ├── ByteBufferRequest.java
│ ├── CollectionFrameDataRequest.java
│ ├── FrameDataRequest.java
│ ├── PingRequest.java
│ ├── PongRequest.java
│ ├── Request.java
│ ├── RequestFactory.java
│ └── StringRequest.java
│ ├── response
│ ├── ByteBufferResponse.java
│ ├── ErrorResponse.java
│ ├── PingResponse.java
│ ├── PongResponse.java
│ ├── Response.java
│ ├── ResponseFactory.java
│ └── TextResponse.java
│ └── util
│ ├── LogImpl.java
│ ├── LogUtil.java
│ ├── Logable.java
│ ├── PermissionUtil.java
│ └── ThreadUtil.java
└── res
└── values
└── strings.xml
/.github/workflows/android.yml:
--------------------------------------------------------------------------------
1 | name: Android CI
2 |
3 | on: [push]
4 |
5 | jobs:
6 | build:
7 |
8 | runs-on: ubuntu-latest
9 |
10 | steps:
11 | - uses: actions/checkout@v1
12 | - name: set up JDK 1.8
13 | uses: actions/setup-java@v1
14 | with:
15 | java-version: 1.8
16 | - name: Build with Gradle
17 | run: ./gradlew build
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | /.gradle
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2019 ZhangKe
2 |
3 | 996 License Version 1.0 (Draft)
4 |
5 | Permission is hereby granted to any individual or legal entity
6 | obtaining a copy of this licensed work (including the source code,
7 | documentation and/or related items, hereinafter collectively referred
8 | to as the "licensed work"), free of charge, to deal with the licensed
9 | work for any purpose, including without limitation, the rights to use,
10 | reproduce, modify, prepare derivative works of, distribute, publish
11 | and sublicense the licensed work, subject to the following conditions:
12 |
13 | 1. The individual or the legal entity must conspicuously display,
14 | without modification, this License and the notice on each redistributed
15 | or derivative copy of the Licensed Work.
16 |
17 | 2. The individual or the legal entity must strictly comply with all
18 | applicable laws, regulations, rules and standards of the jurisdiction
19 | relating to labor and employment where the individual is physically
20 | located or where the individual was born or naturalized; or where the
21 | legal entity is registered or is operating (whichever is stricter). In
22 | case that the jurisdiction has no such laws, regulations, rules and
23 | standards or its laws, regulations, rules and standards are
24 | unenforceable, the individual or the legal entity are required to
25 | comply with Core International Labor Standards.
26 |
27 | 3. The individual or the legal entity shall not induce or force its
28 | employee(s), whether full-time or part-time, or its independent
29 | contractor(s), in any methods, to agree in oral or written form, to
30 | directly or indirectly restrict, weaken or relinquish his or her
31 | rights or remedies under such laws, regulations, rules and standards
32 | relating to labor and employment as mentioned above, no matter whether
33 | such written or oral agreement are enforceable under the laws of the
34 | said jurisdiction, nor shall such individual or the legal entity
35 | limit, in any methods, the rights of its employee(s) or independent
36 | contractor(s) from reporting or complaining to the copyright holder or
37 | relevant authorities monitoring the compliance of the license about
38 | its violation(s) of the said license.
39 |
40 | THE LICENSED WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
41 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
42 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
43 | IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM,
44 | DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
45 | OTHERWISE, ARISING FROM, OUT OF OR IN ANY WAY CONNECTION WITH THE
46 | LICENSED WORK OR THE USE OR OTHER DEALINGS IN THE LICENSED WORK.
47 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext {
5 | compileSdkVersion = 28
6 | minSdkVersion = 15
7 | targetSdkVersion = 28
8 | buildToolsVersion = '28.0.3'
9 | }
10 | repositories {
11 | google()
12 | mavenCentral()
13 | jcenter()
14 | }
15 | dependencies {
16 | classpath 'com.android.tools.build:gradle:3.1.4'
17 |
18 |
19 | // NOTE: Do not place your application dependencies here; they belong
20 | // in the individual module build.gradle files
21 | }
22 | }
23 |
24 | allprojects {
25 | repositories {
26 | google()
27 | mavenCentral()
28 | jcenter()
29 | }
30 | }
31 |
32 | task clean(type: Delete) {
33 | delete rootProject.buildDir
34 | }
35 |
--------------------------------------------------------------------------------
/doc/allclasses-frame.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | 所有类
7 |
8 |
9 |
10 |
11 |
12 | 所有类
13 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/doc/allclasses-noframe.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | 所有类
7 |
8 |
9 |
10 |
11 |
12 | 所有类
13 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/doc/com/zhangke/websocket/WebSocketWrapper.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | WebSocketWrapper
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
44 |
48 |
52 |
55 |
56 |
66 |
67 |
68 |
69 | - 概要:
70 | - 嵌套 |
71 | - 字段 |
72 | - 构造器 |
73 | - 方法
74 |
75 |
76 | - 详细资料:
77 | - 字段 |
78 | - 构造器 |
79 | - 方法
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
91 |
92 |
93 | - java.lang.Object
94 | -
95 |
96 | - com.zhangke.websocket.WebSocketWrapper
97 |
98 |
99 |
100 |
113 |
114 |
115 | -
116 |
117 |
118 | -
119 |
120 |
121 |
方法概要
122 |
123 | -
124 |
125 |
126 |
从类继承的方法 java.lang.Object
127 | clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
154 |
155 |
156 | - 上一个类
157 | - 下一个类
158 |
159 |
163 |
166 |
167 |
177 |
178 |
179 |
180 | - 概要:
181 | - 嵌套 |
182 | - 字段 |
183 | - 构造器 |
184 | - 方法
185 |
186 |
187 | - 详细资料:
188 | - 字段 |
189 | - 构造器 |
190 | - 方法
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
--------------------------------------------------------------------------------
/doc/com/zhangke/websocket/dispatcher/package-frame.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | com.zhangke.websocket.dispatcher
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
接口
15 |
19 |
类
20 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/doc/com/zhangke/websocket/package-frame.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | com.zhangke.websocket
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
接口
15 |
21 |
类
22 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/doc/com/zhangke/websocket/request/package-frame.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | com.zhangke.websocket.request
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
接口
15 |
18 |
类
19 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/doc/com/zhangke/websocket/response/package-frame.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | com.zhangke.websocket.response
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
接口
15 |
18 |
类
19 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/doc/com/zhangke/websocket/util/package-frame.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | com.zhangke.websocket.util
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
接口
15 |
18 |
类
19 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/doc/com/zhangke/websocket/util/package-summary.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | com.zhangke.websocket.util
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
70 |
71 |
74 |
75 |
76 | -
77 |
78 | 接口概要
79 |
80 | 接口 |
81 | 说明 |
82 |
83 |
84 |
85 | Logable |
86 |
87 | 打印日志接口
88 |
89 | Created by ZhangKe on 2019/4/29.
90 | |
91 |
92 |
93 |
94 |
95 | -
96 |
97 | 类概要
98 |
99 | 类 |
100 | 说明 |
101 |
102 |
103 |
104 | LogImpl |
105 |
106 | Logable 默认实现类
107 |
108 | Created by ZhangKe on 2019/4/29.
109 | |
110 |
111 |
112 | LogUtil |
113 |
114 | 日志工具类
115 |
116 | Created by ZhangKe on 2019/3/21.
117 | |
118 |
119 |
120 | PermissionUtil |
121 |
122 | 权限相关工具类
123 |
124 | Created by ZhangKe on 2019/4/29.
125 | |
126 |
127 |
128 | ThreadUtil |
129 |
130 | 线程相关的工具类,
131 | 考虑到后面可能要同时兼容 Java 与 Android,
132 | 所以此处使用工具类收拢入口。
133 | |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
158 |
159 |
160 | - 上一个程序包
161 | - 下一个程序包
162 |
163 |
167 |
170 |
171 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
--------------------------------------------------------------------------------
/doc/com/zhangke/websocket/util/package-tree.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | com.zhangke.websocket.util 类分层结构
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
70 |
71 |
78 |
79 |
类分层结构
80 |
81 | - java.lang.Object
82 |
88 |
89 |
90 |
接口分层结构
91 |
92 | - com.zhangke.websocket.util.Logable
93 |
94 |
95 |
96 |
113 |
114 |
115 | - 上一个
116 | - 下一个
117 |
118 |
122 |
125 |
126 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
--------------------------------------------------------------------------------
/doc/constant-values.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | 常量字段值
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
70 |
71 |
78 |
118 |
119 |
136 |
137 |
138 | - 上一个
139 | - 下一个
140 |
141 |
145 |
148 |
149 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
--------------------------------------------------------------------------------
/doc/deprecated-list.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | 已过时的列表
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
70 |
71 |
75 |
76 |
93 |
120 |
121 |
122 |
123 |
--------------------------------------------------------------------------------
/doc/help-doc.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | API 帮助
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
70 |
71 |
75 |
76 |
77 | -
78 |
概览
79 | 概览 页面是此 API 文档的首页, 提供了所有程序包的列表及其概要。此页面也可能包含这些程序包的总体说明。
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 | 对于所有程序包, 有一个类分层结构页面, 以及每个程序包的分层结构。每个分层结构页面都包含类的列表和接口的列表。从java.lang.Object
开始, 按继承结构对类进行排列。接口不从java.lang.Object
继承。
141 |
142 | - 查看“概览”页面时, 单击 "树" 将显示所有程序包的分层结构。
143 | - 查看特定程序包, 类或接口页面时, 单击 "树" 将仅显示该程序包的分层结构。
144 |
145 |
146 | -
147 |
已过时的 API
148 | 已过时的 API 页面列出了所有已过时的 API。一般由于进行了改进并且通常提供了替代的 API, 所以建议不要使用已过时的 API。在将来的实现过程中, 可能会删除已过时的 API。
149 |
150 | -
151 |
索引
152 | 索引 包含按字母顺序排列的所有类, 接口, 构造器, 方法和字段的列表。
153 |
154 | -
155 |
上一个/下一个
156 | 这些链接使您可以转至下一个或上一个类, 接口, 程序包或相关页面。
157 |
158 | -
159 |
框架/无框架
160 | 这些链接用于显示和隐藏 HTML 框架。所有页面均具有有框架和无框架两种显示方式。
161 |
162 | -
163 |
所有类
164 | 所有类链接显示所有类和接口 (除了非静态嵌套类型)。
165 |
166 | -
167 |
序列化表格
168 | 每个可序列化或可外部化的类都有其序列化字段和方法的说明。此信息对重新实现者有用, 而对使用 API 的开发者则没有什么用处。尽管导航栏中没有链接, 但您可以通过下列方式获取此信息: 转至任何序列化类, 然后单击类说明的 "另请参阅" 部分中的 "序列化表格"。
169 |
170 | -
171 |
常量字段值
172 | 常量字段值页面列出了静态最终字段及其值。
173 |
174 |
175 |
此帮助文件适用于使用标准 doclet 生成的 API 文档。
176 |
177 |
194 |
195 |
196 | - 上一个
197 | - 下一个
198 |
199 |
203 |
206 |
207 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
--------------------------------------------------------------------------------
/doc/index-files/index-1.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | A - 索引
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
44 |
45 | - 上一个字母
46 | - 下一个字母
47 |
48 |
52 |
55 |
56 |
66 |
67 |
68 |
69 |
70 |
71 | A B C D E F G I L M N O P R S T V W
72 |
73 |
74 |
A
75 |
76 | - addListener(SocketListener) - 类 中的方法com.zhangke.websocket.dispatcher.MainThreadResponseDelivery
77 | -
78 | - addListener(SocketListener) - 接口 中的方法com.zhangke.websocket.dispatcher.ResponseDelivery
79 | -
80 | - addListener(SocketListener) - 类 中的方法com.zhangke.websocket.WebSocketManager
81 | -
82 |
84 |
85 |
86 |
A B C D E F G I L M N O P R S T V W
87 |
88 |
105 |
106 |
107 | - 上一个字母
108 | - 下一个字母
109 |
110 |
114 |
117 |
118 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
--------------------------------------------------------------------------------
/doc/index-files/index-10.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | M - 索引
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
70 |
71 | A B C D E F G I L M N O P R S T V W
72 |
73 |
74 |
M
75 |
76 | - MainThreadResponseDelivery - com.zhangke.websocket.dispatcher中的类
77 | -
78 |
用户注册的消息发射器,
79 | 内部维护一个
SocketListener
的 List,
80 | 调用每一个方法都会通知 List 中所有的 Listener,
81 | 这么做主要为了统一控制消息的回调线程以及简化代码。
82 |
83 | - MainThreadResponseDelivery() - 类 的构造器com.zhangke.websocket.dispatcher.MainThreadResponseDelivery
84 | -
85 |
86 |
A B C D E F G I L M N O P R S T V W
87 |
88 |
105 |
132 |
133 |
134 |
135 |
--------------------------------------------------------------------------------
/doc/index-files/index-11.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | N - 索引
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
70 |
71 | A B C D E F G I L M N O P R S T V W
72 |
73 |
74 |
N
75 |
76 | - NetworkChangedReceiver - com.zhangke.websocket中的类
77 | -
78 |
监听网络变化广播,网络变化时自动重连
79 | Created by ZhangKe on 2018/7/2.
80 |
81 | - NetworkChangedReceiver() - 类 的构造器com.zhangke.websocket.NetworkChangedReceiver
82 | -
83 |
84 |
A B C D E F G I L M N O P R S T V W
85 |
86 |
103 |
130 |
131 |
132 |
133 |
--------------------------------------------------------------------------------
/doc/index-files/index-2.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | B - 索引
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
70 |
71 | A B C D E F G I L M N O P R S T V W
72 |
73 |
74 |
B
75 |
76 | - ByteArrayRequest - com.zhangke.websocket.request中的类
77 | -
78 |
byte[] 类型的请求
79 |
80 | Created by ZhangKe on 2019/3/22.
81 |
82 | - ByteBufferRequest - com.zhangke.websocket.request中的类
83 | -
84 |
ByteBuffer 类型的请求
85 |
86 | Created by ZhangKe on 2019/3/22.
87 |
88 | - ByteBufferResponse - com.zhangke.websocket.response中的类
89 | -
90 |
接收到二进制数据
91 |
92 | Created by ZhangKe on 2019/3/22.
93 |
94 |
95 |
A B C D E F G I L M N O P R S T V W
96 |
97 |
114 |
141 |
142 |
143 |
144 |
--------------------------------------------------------------------------------
/doc/index-files/index-6.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | F - 索引
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
70 |
71 | A B C D E F G I L M N O P R S T V W
72 |
73 |
74 |
F
75 |
76 | - FrameDataRequest - com.zhangke.websocket.request中的类
77 | -
78 |
发送 Framedata
79 |
80 | Created by ZhangKe on 2019/3/28.
81 |
82 |
83 |
A B C D E F G I L M N O P R S T V W
84 |
85 |
102 |
129 |
130 |
131 |
132 |
--------------------------------------------------------------------------------
/doc/index-files/index-9.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | L - 索引
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
70 |
71 | A B C D E F G I L M N O P R S T V W
72 |
73 |
74 |
L
75 |
76 | - Logable - com.zhangke.websocket.util中的接口
77 | -
78 |
打印日志接口
79 |
80 | Created by ZhangKe on 2019/4/29.
81 |
82 | - LogImpl - com.zhangke.websocket.util中的类
83 | -
84 |
Logable 默认实现类
85 |
86 | Created by ZhangKe on 2019/4/29.
87 |
88 | - LogImpl() - 类 的构造器com.zhangke.websocket.util.LogImpl
89 | -
90 | - LogUtil - com.zhangke.websocket.util中的类
91 | -
92 |
日志工具类
93 |
94 | Created by ZhangKe on 2019/3/21.
95 |
96 | - LogUtil() - 类 的构造器com.zhangke.websocket.util.LogUtil
97 | -
98 |
99 |
A B C D E F G I L M N O P R S T V W
100 |
101 |
118 |
145 |
146 |
147 |
148 |
--------------------------------------------------------------------------------
/doc/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | 生成的文档 (无标题)
7 |
60 |
61 |
75 |
76 |
--------------------------------------------------------------------------------
/doc/overview-frame.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | 概览列表
7 |
8 |
9 |
10 |
11 |
12 |
13 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/doc/overview-summary.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | 概览
7 |
8 |
9 |
10 |
11 |
12 |
22 |
25 |
26 |
43 |
70 |
71 |
102 |
103 |
120 |
121 |
122 | - 上一个
123 | - 下一个
124 |
125 |
129 |
132 |
133 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
--------------------------------------------------------------------------------
/doc/package-list:
--------------------------------------------------------------------------------
1 | com.zhangke.websocket
2 | com.zhangke.websocket.dispatcher
3 | com.zhangke.websocket.request
4 | com.zhangke.websocket.response
5 | com.zhangke.websocket.util
6 |
--------------------------------------------------------------------------------
/doc/script.js:
--------------------------------------------------------------------------------
1 | function show(type)
2 | {
3 | count = 0;
4 | for (var key in methods) {
5 | var row = document.getElementById(key);
6 | if ((methods[key] & type) != 0) {
7 | row.style.display = '';
8 | row.className = (count++ % 2) ? rowColor : altColor;
9 | }
10 | else
11 | row.style.display = 'none';
12 | }
13 | updateTabs(type);
14 | }
15 |
16 | function updateTabs(type)
17 | {
18 | for (var value in tabs) {
19 | var sNode = document.getElementById(tabs[value][0]);
20 | var spanNode = sNode.firstChild;
21 | if (value == type) {
22 | sNode.className = activeTableTab;
23 | spanNode.innerHTML = tabs[value][1];
24 | }
25 | else {
26 | sNode.className = tableTab;
27 | spanNode.innerHTML = "" + tabs[value][1] + "";
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/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/0xZhangKe/WebSocketDemo/df9f1b8c0fa40444198aa6c6f4c9c0f7332b2539/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Nov 07 10:33:11 CST 2017
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-4.4-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 |
--------------------------------------------------------------------------------
/image/dispatcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/0xZhangKe/WebSocketDemo/df9f1b8c0fa40444198aa6c6f4c9c0f7332b2539/image/dispatcher.png
--------------------------------------------------------------------------------
/image/qrcode_for_account.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/0xZhangKe/WebSocketDemo/df9f1b8c0fa40444198aa6c6f4c9c0f7332b2539/image/qrcode_for_account.jpg
--------------------------------------------------------------------------------
/image/qrcode_for_gsubscription.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/0xZhangKe/WebSocketDemo/df9f1b8c0fa40444198aa6c6f4c9c0f7332b2539/image/qrcode_for_gsubscription.jpg
--------------------------------------------------------------------------------
/image/websocketservice.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/0xZhangKe/WebSocketDemo/df9f1b8c0fa40444198aa6c6f4c9c0f7332b2539/image/websocketservice.png
--------------------------------------------------------------------------------
/image/websocketthread.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/0xZhangKe/WebSocketDemo/df9f1b8c0fa40444198aa6c6f4c9c0f7332b2539/image/websocketthread.png
--------------------------------------------------------------------------------
/samples/dispatersample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/samples/dispatersample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion rootProject.ext.compileSdkVersion
5 | buildToolsVersion rootProject.ext.buildToolsVersion
6 | defaultConfig {
7 | applicationId "com.zhangke.smaple.dispatersample"
8 | minSdkVersion rootProject.ext.minSdkVersion
9 | targetSdkVersion rootProject.ext.targetSdkVersion
10 | versionCode 3
11 | versionName "3.0"
12 | }
13 |
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 |
21 | }
22 |
23 | dependencies {
24 | implementation fileTree(dir: 'libs', include: ['*.jar'])
25 |
26 | implementation 'androidx.appcompat:appcompat:1.0.2'
27 | implementation 'com.alibaba:fastjson:1.2.33'
28 | implementation project(':websocketlib')
29 | }
30 |
--------------------------------------------------------------------------------
/samples/dispatersample/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/samples/dispatersample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/samples/dispatersample/src/main/java/com/zhangke/smaple/dispatersample/App.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.smaple.dispatersample;
2 |
3 | import android.app.Application;
4 |
5 | import com.zhangke.websocket.WebSocketHandler;
6 | import com.zhangke.websocket.WebSocketManager;
7 | import com.zhangke.websocket.WebSocketSetting;
8 |
9 | /**
10 | * Created by ZhangKe on 2018/6/27.
11 | */
12 | public class App extends Application {
13 |
14 | @Override
15 | public void onCreate() {
16 | super.onCreate();
17 |
18 | initWebSocket();
19 | }
20 |
21 | private void initWebSocket(){
22 | WebSocketSetting setting = new WebSocketSetting();
23 | //连接地址,必填,例如 wss://echo.websocket.org
24 | setting.setConnectUrl("your connect url");//必填
25 |
26 | //设置连接超时时间
27 | setting.setConnectTimeout(15 * 1000);
28 |
29 | //设置心跳间隔时间
30 | setting.setConnectionLostTimeout(60);
31 |
32 | //设置断开后的重连次数,可以设置的很大,不会有什么性能上的影响
33 | setting.setReconnectFrequency(60);
34 |
35 | // //设置Header
36 | // setting.setHttpHeaders(header);
37 |
38 | //设置消息分发器,接收到数据后先进入该类中处理,处理完再发送到下游
39 | setting.setResponseProcessDispatcher(new AppResponseDispatcher());
40 | //接收到数据后是否放入子线程处理,只有设置了 ResponseProcessDispatcher 才有意义
41 | setting.setProcessDataOnBackground(true);
42 |
43 | //网络状态发生变化后是否重连,
44 | //需要调用 WebSocketHandler.registerNetworkChangedReceiver(context) 方法注册网络监听广播
45 | setting.setReconnectWithNetworkChanged(true);
46 |
47 | //通过 init 方法初始化默认的 WebSocketManager 对象
48 | WebSocketManager manager = WebSocketHandler.init(setting);
49 | //启动连接
50 | manager.start();
51 |
52 | //注意,需要在 AndroidManifest 中配置网络状态获取权限
53 | //注册网路连接状态变化广播
54 | WebSocketHandler.registerNetworkChangedReceiver(this);
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/samples/dispatersample/src/main/java/com/zhangke/smaple/dispatersample/AppResponseDispatcher.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.smaple.dispatersample;
2 |
3 | import com.alibaba.fastjson.JSON;
4 | import com.alibaba.fastjson.JSONException;
5 | import com.alibaba.fastjson.TypeReference;
6 | import com.zhangke.websocket.SimpleDispatcher;
7 | import com.zhangke.websocket.dispatcher.ResponseDelivery;
8 | import com.zhangke.websocket.response.ErrorResponse;
9 | import com.zhangke.websocket.response.Response;
10 | import com.zhangke.websocket.response.ResponseFactory;
11 |
12 | /**
13 | * 消息分发器
14 | *
15 | * Created by ZhangKe on 2018/6/27.
16 | */
17 | public class AppResponseDispatcher extends SimpleDispatcher {
18 |
19 | /**
20 | * JSON 数据格式错误
21 | */
22 | public static final int JSON_ERROR = 11;
23 | /**
24 | * code 码错误
25 | */
26 | public static final int CODE_ERROR = 12;
27 |
28 | @Override
29 | public void onMessage(String message, ResponseDelivery delivery) {
30 | try {
31 | CommonResponseEntity response = JSON.parseObject(message, new TypeReference() {
32 | });
33 | if (response.getCode() >= 1000 && response.getCode() < 2000) {
34 | delivery.onMessage(message, response);
35 | } else {
36 | ErrorResponse errorResponse = ResponseFactory.createErrorResponse();
37 | errorResponse.setErrorCode(CODE_ERROR);
38 | Response textResponse = ResponseFactory.createTextResponse();
39 | textResponse.setResponseData(message);
40 | errorResponse.setResponseData(textResponse);
41 | errorResponse.setReserved(response);
42 | onSendDataError(errorResponse, delivery);
43 | }
44 | } catch (JSONException e) {
45 | ErrorResponse errorResponse = ResponseFactory.createErrorResponse();
46 | Response textResponse = ResponseFactory.createTextResponse();
47 | textResponse.setResponseData(message);
48 | errorResponse.setResponseData(textResponse);
49 | errorResponse.setErrorCode(JSON_ERROR);
50 | errorResponse.setCause(e);
51 | onSendDataError(errorResponse, delivery);
52 | }
53 | }
54 |
55 | /**
56 | * 统一处理错误信息,
57 | * 界面上可使用 ErrorResponse#getDescription() 来当做提示语
58 | */
59 | @Override
60 | public void onSendDataError(ErrorResponse error, ResponseDelivery delivery) {
61 | switch (error.getErrorCode()) {
62 | case ErrorResponse.ERROR_NO_CONNECT:
63 | error.setDescription("网络错误");
64 | break;
65 | case ErrorResponse.ERROR_UN_INIT:
66 | error.setDescription("连接未初始化");
67 | break;
68 | case ErrorResponse.ERROR_UNKNOWN:
69 | error.setDescription("未知错误");
70 | break;
71 | case JSON_ERROR:
72 | error.setDescription("数据格式异常");
73 | break;
74 | case CODE_ERROR:
75 | error.setDescription("响应码错误");
76 | break;
77 | }
78 | delivery.onSendDataError(error);
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/samples/dispatersample/src/main/java/com/zhangke/smaple/dispatersample/CommonResponseEntity.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.smaple.dispatersample;
2 |
3 | /**
4 | * 后台接口返回的数据格式
5 | * Created by ZhangKe on 2018/6/27.
6 | */
7 | public class CommonResponseEntity {
8 |
9 | private String message;
10 | private String data;
11 | private int code;
12 | private String path;
13 |
14 | public String getMessage() {
15 | return message;
16 | }
17 |
18 | public void setMessage(String message) {
19 | this.message = message;
20 | }
21 |
22 | public String getData() {
23 | return data;
24 | }
25 |
26 | public void setData(String data) {
27 | this.data = data;
28 | }
29 |
30 | public int getCode() {
31 | return code;
32 | }
33 |
34 | public void setCode(int code) {
35 | this.code = code;
36 | }
37 |
38 | public String getPath() {
39 | return path;
40 | }
41 |
42 | public void setPath(String path) {
43 | this.path = path;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/samples/dispatersample/src/main/java/com/zhangke/smaple/dispatersample/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.smaple.dispatersample;
2 |
3 | import android.os.Bundle;
4 | import android.text.TextUtils;
5 | import android.view.View;
6 | import android.widget.EditText;
7 | import android.widget.ScrollView;
8 | import android.widget.TextView;
9 | import android.widget.Toast;
10 |
11 | import androidx.appcompat.app.AppCompatActivity;
12 |
13 | import com.zhangke.websocket.SimpleListener;
14 | import com.zhangke.websocket.SocketListener;
15 | import com.zhangke.websocket.WebSocketHandler;
16 | import com.zhangke.websocket.response.ErrorResponse;
17 |
18 | import org.java_websocket.framing.Framedata;
19 |
20 | import java.nio.ByteBuffer;
21 |
22 | public class MainActivity extends AppCompatActivity {
23 |
24 | private EditText etContent;
25 | private TextView tvMsg;
26 | private ScrollView scrollView;
27 |
28 | private SocketListener socketListener = new SimpleListener() {
29 | @Override
30 | public void onConnected() {
31 | appendMsgDisplay("onConnected");
32 | }
33 |
34 | @Override
35 | public void onConnectFailed(Throwable e) {
36 | if (e != null) {
37 | appendMsgDisplay("onConnectFailed:" + e.toString());
38 | } else {
39 | appendMsgDisplay("onConnectFailed:null");
40 | }
41 | }
42 |
43 | @Override
44 | public void onDisconnect() {
45 | appendMsgDisplay("onDisconnect");
46 | }
47 |
48 | @Override
49 | public void onSendDataError(ErrorResponse errorResponse) {
50 | appendMsgDisplay(errorResponse.getDescription());
51 | errorResponse.release();
52 | }
53 |
54 | @Override
55 | public void onMessage(String message, T data) {
56 | if (data instanceof CommonResponseEntity) {
57 | CommonResponseEntity responseEntity = (CommonResponseEntity) data;
58 | appendMsgDisplay(responseEntity.getMessage());
59 | }
60 | }
61 | };
62 |
63 | @Override
64 | protected void onCreate(Bundle savedInstanceState) {
65 | super.onCreate(savedInstanceState);
66 | setContentView(R.layout.activity_main);
67 |
68 | initView();
69 |
70 | WebSocketHandler.getDefault().addListener(socketListener);
71 |
72 | }
73 |
74 | private void initView() {
75 | etContent = (EditText) findViewById(R.id.et_content);
76 | tvMsg = (TextView) findViewById(R.id.tv_msg);
77 | scrollView = (ScrollView) findViewById(R.id.scroll_view);
78 |
79 | findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
80 | @Override
81 | public void onClick(View v) {
82 | String text = etContent.getText().toString();
83 | if (TextUtils.isEmpty(text)) {
84 | Toast.makeText(MainActivity.this, "输入不能为空", Toast.LENGTH_SHORT).show();
85 | return;
86 | }
87 | WebSocketHandler.getDefault().send(text);
88 | }
89 | });
90 | }
91 |
92 | @Override
93 | protected void onDestroy() {
94 | super.onDestroy();
95 | WebSocketHandler.getDefault().removeListener(socketListener);
96 | }
97 |
98 | private void appendMsgDisplay(String msg) {
99 | StringBuilder textBuilder = new StringBuilder();
100 | if (!TextUtils.isEmpty(tvMsg.getText())) {
101 | textBuilder.append(tvMsg.getText().toString());
102 | textBuilder.append("\n");
103 | }
104 | textBuilder.append(msg);
105 | textBuilder.append("\n");
106 | tvMsg.setText(textBuilder.toString());
107 | tvMsg.post(new Runnable() {
108 | @Override
109 | public void run() {
110 | scrollView.fullScroll(ScrollView.FOCUS_DOWN);
111 | }
112 | });
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/samples/dispatersample/src/main/res/drawable/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/0xZhangKe/WebSocketDemo/df9f1b8c0fa40444198aa6c6f4c9c0f7332b2539/samples/dispatersample/src/main/res/drawable/ic_launcher.png
--------------------------------------------------------------------------------
/samples/dispatersample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
19 |
20 |
27 |
28 |
34 |
35 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/samples/dispatersample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/samples/dispatersample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | dispatersample
3 |
4 |
--------------------------------------------------------------------------------
/samples/dispatersample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/samples/simple/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/samples/simple/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion rootProject.ext.compileSdkVersion
5 | buildToolsVersion rootProject.ext.buildToolsVersion
6 | defaultConfig {
7 | minSdkVersion rootProject.ext.minSdkVersion
8 | targetSdkVersion rootProject.ext.targetSdkVersion
9 | applicationId "com.zhangke.smaple.simple"
10 | versionCode 3
11 | versionName "3.0"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | implementation fileTree(include: ['*.jar'], dir: 'libs')
23 |
24 | implementation 'androidx.appcompat:appcompat:1.0.2'
25 | implementation 'com.alibaba:fastjson:1.2.33'
26 | implementation project(':websocketlib')
27 | }
28 |
--------------------------------------------------------------------------------
/samples/simple/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/samples/simple/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/samples/simple/src/main/java/com/zhangke/websocketdemo/App.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocketdemo;
2 |
3 | import android.app.Application;
4 |
5 | import com.zhangke.websocket.WebSocketHandler;
6 | import com.zhangke.websocket.WebSocketManager;
7 | import com.zhangke.websocket.WebSocketSetting;
8 |
9 | /**
10 | * Created by ZhangKe on 2018/6/27.
11 | */
12 | public class App extends Application {
13 |
14 | @Override
15 | public void onCreate() {
16 | super.onCreate();
17 |
18 | initWebSocket();
19 | }
20 |
21 | private void initWebSocket(){
22 | WebSocketSetting setting = new WebSocketSetting();
23 | //连接地址,必填,例如 wss://echo.websocket.org
24 | setting.setConnectUrl("your connect url");//必填
25 |
26 | //设置连接超时时间
27 | setting.setConnectTimeout(15 * 1000);
28 |
29 | //设置心跳间隔时间
30 | setting.setConnectionLostTimeout(60);
31 |
32 | //设置断开后的重连次数,可以设置的很大,不会有什么性能上的影响
33 | setting.setReconnectFrequency(60);
34 |
35 | //网络状态发生变化后是否重连,
36 | //需要调用 WebSocketHandler.registerNetworkChangedReceiver(context) 方法注册网络监听广播
37 | setting.setReconnectWithNetworkChanged(true);
38 |
39 | //通过 init 方法初始化默认的 WebSocketManager 对象
40 | WebSocketManager manager = WebSocketHandler.init(setting);
41 | //启动连接
42 | manager.start();
43 |
44 | //注意,需要在 AndroidManifest 中配置网络状态获取权限
45 | //注册网路连接状态变化广播
46 | WebSocketHandler.registerNetworkChangedReceiver(this);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/samples/simple/src/main/java/com/zhangke/websocketdemo/TestActivity.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocketdemo;
2 |
3 | import android.os.Bundle;
4 | import android.text.TextUtils;
5 | import android.view.View;
6 | import android.widget.EditText;
7 | import android.widget.ScrollView;
8 | import android.widget.TextView;
9 |
10 | import androidx.appcompat.app.AppCompatActivity;
11 |
12 | import com.zhangke.websocket.SimpleListener;
13 | import com.zhangke.websocket.SocketListener;
14 | import com.zhangke.websocket.WebSocketHandler;
15 | import com.zhangke.websocket.response.ErrorResponse;
16 |
17 | import org.java_websocket.framing.Framedata;
18 |
19 | import java.nio.ByteBuffer;
20 |
21 | public class TestActivity extends AppCompatActivity {
22 |
23 | private EditText etContent;
24 | private TextView tvMsg;
25 | private ScrollView scrollView;
26 |
27 | private SocketListener socketListener = new SimpleListener() {
28 | @Override
29 | public void onConnected() {
30 | appendMsgDisplay("onConnected");
31 | }
32 |
33 | @Override
34 | public void onConnectFailed(Throwable e) {
35 | if (e != null) {
36 | appendMsgDisplay("onConnectFailed:" + e.toString());
37 | } else {
38 | appendMsgDisplay("onConnectFailed:null");
39 | }
40 | }
41 |
42 | @Override
43 | public void onDisconnect() {
44 | appendMsgDisplay("onDisconnect");
45 | }
46 |
47 | @Override
48 | public void onSendDataError(ErrorResponse errorResponse) {
49 | appendMsgDisplay("onSendDataError:" + errorResponse.toString());
50 | errorResponse.release();
51 | }
52 |
53 | @Override
54 | public void onMessage(String message, T data) {
55 | appendMsgDisplay("onMessage(String, T):" + message);
56 | }
57 |
58 | @Override
59 | public void onMessage(ByteBuffer bytes, T data) {
60 | appendMsgDisplay("onMessage(ByteBuffer, T):" + bytes);
61 | }
62 | };
63 |
64 | @Override
65 | protected void onCreate(Bundle savedInstanceState) {
66 | super.onCreate(savedInstanceState);
67 | setContentView(R.layout.activity_test);
68 |
69 | initView();
70 |
71 | WebSocketHandler.getDefault().addListener(socketListener);
72 |
73 | }
74 |
75 | private void initView() {
76 | etContent = (EditText) findViewById(R.id.et_content);
77 | tvMsg = (TextView) findViewById(R.id.tv_msg);
78 | scrollView = (ScrollView) findViewById(R.id.scroll_view);
79 |
80 | findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
81 | @Override
82 | public void onClick(View v) {
83 | String text = etContent.getText().toString();
84 | if (TextUtils.isEmpty(text)) {
85 | UiUtil.showToast(TestActivity.this, "输入不能为空");
86 | return;
87 | }
88 | WebSocketHandler.getDefault().send(text);
89 | }
90 | });
91 | findViewById(R.id.btn_reconnect).setOnClickListener(new View.OnClickListener() {
92 | @Override
93 | public void onClick(View v) {
94 | // WebSocketSetting setting = WebSocketHandler.getDefault().getSetting();
95 | // setting.setConnectUrl("other url");
96 | // WebSocketHandler.getDefault().reconnect(setting);
97 | WebSocketHandler.getDefault().reconnect();
98 | }
99 | });
100 | findViewById(R.id.btn_disconnect).setOnClickListener(new View.OnClickListener() {
101 | @Override
102 | public void onClick(View v) {
103 | WebSocketHandler.getDefault().disConnect();
104 | }
105 | });
106 | findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() {
107 | @Override
108 | public void onClick(View v) {
109 | tvMsg.setText("");
110 | }
111 | });
112 | }
113 |
114 | @Override
115 | protected void onDestroy() {
116 | super.onDestroy();
117 | WebSocketHandler.getDefault().removeListener(socketListener);
118 | }
119 |
120 | private void appendMsgDisplay(String msg) {
121 | StringBuilder textBuilder = new StringBuilder();
122 | if (!TextUtils.isEmpty(tvMsg.getText())) {
123 | textBuilder.append(tvMsg.getText().toString());
124 | textBuilder.append("\n");
125 | }
126 | textBuilder.append(msg);
127 | textBuilder.append("\n");
128 | tvMsg.setText(textBuilder.toString());
129 | tvMsg.post(new Runnable() {
130 | @Override
131 | public void run() {
132 | scrollView.fullScroll(ScrollView.FOCUS_DOWN);
133 | }
134 | });
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/samples/simple/src/main/java/com/zhangke/websocketdemo/UiUtil.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocketdemo;
2 |
3 | import android.content.Context;
4 | import android.view.Gravity;
5 | import android.widget.Toast;
6 |
7 | /**
8 | * Created by ZhangKe on 2018/6/25.
9 | */
10 | public class UiUtil {
11 |
12 | private static Toast toast;
13 |
14 | public static void showToast(final Context context, final String message) {
15 | showToast(context, message, false);
16 | }
17 |
18 | public static void showToast(final Context context, final String message, final boolean center) {
19 | if (toast == null) {
20 | toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
21 | } else {
22 | toast.setText(message);
23 | }
24 | if (center) {
25 | toast.setGravity(Gravity.CENTER, 0, 0);
26 | }
27 | toast.show();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/samples/simple/src/main/res/drawable/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/0xZhangKe/WebSocketDemo/df9f1b8c0fa40444198aa6c6f4c9c0f7332b2539/samples/simple/src/main/res/drawable/ic_launcher.png
--------------------------------------------------------------------------------
/samples/simple/src/main/res/layout/activity_test.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
19 |
20 |
27 |
28 |
33 |
34 |
39 |
40 |
45 |
46 |
51 |
52 |
53 |
54 |
55 |
61 |
62 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/samples/simple/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/samples/simple/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | WebSocketDemo
3 |
4 |
--------------------------------------------------------------------------------
/samples/simple/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':websocketlib'
2 | include ':samples:dispatersample'
3 | include ':samples:simple'
--------------------------------------------------------------------------------
/websocketlib/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/websocketlib/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion rootProject.ext.compileSdkVersion
5 | buildToolsVersion rootProject.ext.buildToolsVersion
6 |
7 |
8 |
9 | defaultConfig {
10 | minSdkVersion rootProject.ext.minSdkVersion
11 | targetSdkVersion rootProject.ext.targetSdkVersion
12 | versionCode 3
13 | versionName "3.0"
14 |
15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
16 |
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 |
26 | }
27 |
28 | dependencies {
29 | implementation fileTree(dir: 'libs', include: ['*.jar'])
30 | api 'org.java-websocket:Java-WebSocket:1.4.0'
31 | }
32 |
--------------------------------------------------------------------------------
/websocketlib/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/websocketlib/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/DefaultReconnectManager.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket;
2 |
3 | import com.zhangke.websocket.util.LogUtil;
4 |
5 | import java.util.concurrent.ExecutorService;
6 | import java.util.concurrent.Executors;
7 | import java.util.concurrent.RejectedExecutionException;
8 |
9 | /**
10 | * 负责 WebSocket 重连
11 | *
12 | * Created by ZhangKe on 2018/6/24.
13 | */
14 | public class DefaultReconnectManager implements ReconnectManager {
15 |
16 | private static final String TAG = "WSDefaultRM";
17 |
18 | /**
19 | * 重连锁
20 | */
21 | private final Object BLOCK = new Object();
22 |
23 | private WebSocketManager mWebSocketManager;
24 | private OnConnectListener mOnDisconnectListener;
25 |
26 | /**
27 | * 是否正在重连
28 | */
29 | private volatile boolean reconnecting;
30 | /**
31 | * 被销毁
32 | */
33 | private volatile boolean destroyed;
34 | /**
35 | * 是否需要停止重连
36 | */
37 | private volatile boolean needStopReconnect = false;
38 | /**
39 | * 是否已连接
40 | */
41 | private volatile boolean connected = false;
42 |
43 | private final ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
44 |
45 | public DefaultReconnectManager(WebSocketManager webSocketManager,
46 | OnConnectListener onDisconnectListener) {
47 | this.mWebSocketManager = webSocketManager;
48 | this.mOnDisconnectListener = onDisconnectListener;
49 | reconnecting = false;
50 | destroyed = false;
51 | }
52 |
53 | @Override
54 | public boolean reconnecting() {
55 | return reconnecting;
56 | }
57 |
58 | @Override
59 | public void startReconnect() {
60 | if (reconnecting) {
61 | LogUtil.i(TAG, "Reconnecting, do not call again.");
62 | return;
63 | }
64 | if (destroyed) {
65 | LogUtil.e(TAG, "ReconnectManager is destroyed!!!");
66 | return;
67 | }
68 | needStopReconnect = false;
69 | reconnecting = true;
70 | try {
71 | singleThreadPool.execute(getReconnectRunnable());
72 | } catch (RejectedExecutionException e) {
73 | LogUtil.e(TAG, "线程队列已满,无法执行此次任务。", e);
74 | reconnecting = false;
75 | }
76 | }
77 |
78 | private int reconnectCount = 1;
79 | private int finishCount = 1;
80 |
81 | private Runnable getReconnectRunnable() {
82 | return new Runnable() {
83 | @Override
84 | public void run() {
85 | if (destroyed || needStopReconnect) {
86 | reconnecting = false;
87 | return;
88 | }
89 | LogUtil.d(TAG, "开始重连:" + reconnectCount);
90 | reconnectCount++;
91 | reconnecting = true;
92 | connected = false;
93 | try {
94 | int count = mWebSocketManager.getSetting().getReconnectFrequency();
95 | for (int i = 0; i < count; i++) {
96 | LogUtil.i(TAG, String.format("第%s次重连", i + 1));
97 | mWebSocketManager.reconnectOnce();
98 | synchronized (BLOCK) {
99 | try {
100 | BLOCK.wait(mWebSocketManager.getSetting().getConnectTimeout());
101 | if (connected) {
102 | LogUtil.i(TAG, "reconnectOnce success!");
103 | mOnDisconnectListener.onConnected();
104 | return;
105 | }
106 | if (needStopReconnect) {
107 | break;
108 | }
109 | } catch (InterruptedException e) {
110 | break;
111 | }
112 | }
113 | }
114 | //重连失败
115 | LogUtil.i(TAG, "reconnectOnce failed!");
116 | mOnDisconnectListener.onDisconnect();
117 | } finally {
118 | LogUtil.d(TAG, "重连结束:" + finishCount);
119 | finishCount++;
120 | reconnecting = false;
121 | LogUtil.i(TAG, "reconnecting = false");
122 | }
123 | }
124 | };
125 | }
126 |
127 | @Override
128 | public void stopReconnect() {
129 | needStopReconnect = true;
130 | if (singleThreadPool != null) {
131 | singleThreadPool.shutdownNow();
132 | }
133 | }
134 |
135 | @Override
136 | public void onConnected() {
137 | connected = true;
138 | synchronized (BLOCK) {
139 | LogUtil.i(TAG, "onConnected()->BLOCK.notifyAll()");
140 | BLOCK.notifyAll();
141 | }
142 | }
143 |
144 | @Override
145 | public void onConnectError(Throwable th) {
146 | connected = false;
147 | synchronized (BLOCK) {
148 | LogUtil.i(TAG, "onConnectError(Throwable)->BLOCK.notifyAll()");
149 | BLOCK.notifyAll();
150 | }
151 | }
152 |
153 | /**
154 | * 销毁资源,并停止重连
155 | */
156 | @Override
157 | public void destroy() {
158 | destroyed = true;
159 | stopReconnect();
160 | mWebSocketManager = null;
161 | }
162 | }
163 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/NetworkChangedReceiver.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket;
2 |
3 | import android.Manifest;
4 | import android.content.BroadcastReceiver;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.net.ConnectivityManager;
8 | import android.net.NetworkInfo;
9 |
10 | import com.zhangke.websocket.util.LogUtil;
11 | import com.zhangke.websocket.util.PermissionUtil;
12 |
13 | import java.util.Map;
14 |
15 | /**
16 | * 监听网络变化广播,网络变化时自动重连
17 | * Created by ZhangKe on 2018/7/2.
18 | */
19 | public class NetworkChangedReceiver extends BroadcastReceiver {
20 |
21 | private static final String TAG = "WSNetworkReceiver";
22 |
23 | public NetworkChangedReceiver() {
24 | }
25 |
26 | @Override
27 | public void onReceive(Context context, Intent intent) {
28 | if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
29 | ConnectivityManager manager = (ConnectivityManager) context
30 | .getSystemService(Context.CONNECTIVITY_SERVICE);
31 | if (manager == null) return;
32 | try {
33 | if (PermissionUtil.checkPermission(context, Manifest.permission.ACCESS_NETWORK_STATE)) {
34 | NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
35 | if (activeNetwork != null) {
36 | if (activeNetwork.isConnected()) {
37 | if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
38 | LogUtil.i(TAG, "网络连接发生变化,当前WiFi连接可用,正在尝试重连。");
39 | } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
40 | LogUtil.i(TAG, "网络连接发生变化,当前移动连接可用,正在尝试重连。");
41 | }
42 | if (WebSocketHandler.getDefault() != null) {
43 | if (WebSocketHandler.getDefault().getSetting().reconnectWithNetworkChanged()) {
44 | WebSocketHandler.getDefault().reconnect();
45 | }
46 | }
47 | if (!WebSocketHandler.getAllWebSocket().isEmpty()) {
48 | Map webSocketManagerMap = WebSocketHandler.getAllWebSocket();
49 | for (String key : webSocketManagerMap.keySet()) {
50 | WebSocketManager item = webSocketManagerMap.get(key);
51 | if (item != null && item.getSetting().reconnectWithNetworkChanged()) {
52 | item.reconnect();
53 | }
54 | }
55 | }
56 | } else {
57 | LogUtil.i(TAG, "当前没有可用网络");
58 | }
59 | }
60 | }
61 | } catch (Exception e) {
62 | LogUtil.e(TAG, "网络状态获取错误", e);
63 | }
64 | }
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/ReconnectManager.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket;
2 |
3 | /**
4 | * 重连接口
5 | *
6 | * Created by ZhangKe on 2019/3/27.
7 | */
8 | public interface ReconnectManager {
9 |
10 | /**
11 | * 是否正在重连
12 | */
13 | boolean reconnecting();
14 |
15 | /**
16 | * 开始重连
17 | */
18 | void startReconnect();
19 |
20 | /**
21 | * 停止重连
22 | */
23 | void stopReconnect();
24 |
25 | /**
26 | * 连接成功
27 | */
28 | void onConnected();
29 |
30 | /**
31 | * 连接失败
32 | *
33 | * @param th 失败原因
34 | */
35 | void onConnectError(Throwable th);
36 |
37 | /**
38 | * 销毁资源
39 | */
40 | void destroy();
41 |
42 | /**
43 | * 连接成功或失败事件
44 | */
45 | interface OnConnectListener {
46 | void onConnected();
47 |
48 | void onDisconnect();
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/SimpleDispatcher.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket;
2 |
3 | import com.zhangke.websocket.dispatcher.IResponseDispatcher;
4 | import com.zhangke.websocket.dispatcher.ResponseDelivery;
5 |
6 | import org.java_websocket.framing.Framedata;
7 |
8 | import java.nio.ByteBuffer;
9 |
10 | /**
11 | * 一个简单的 WebSocket 消息分发器,实现了 {@link IResponseDispatcher} 接口,
12 | * 因为 IResponseDispatcher 中的方法比较多,所以在此提供了一个简单版本,
13 | * 只需要实现其中主要的几个方法即可。
14 | *
15 | * Created by ZhangKe on 2019/4/2.
16 | */
17 | public abstract class SimpleDispatcher implements IResponseDispatcher {
18 |
19 | @Override
20 | public void onConnected(ResponseDelivery delivery) {
21 | delivery.onConnected();
22 | }
23 |
24 | @Override
25 | public void onConnectFailed(Throwable cause, ResponseDelivery delivery) {
26 | delivery.onConnectFailed(cause);
27 | }
28 |
29 | @Override
30 | public void onDisconnect(ResponseDelivery delivery) {
31 | delivery.onDisconnect();
32 | }
33 |
34 | @Override
35 | public void onMessage(ByteBuffer byteBuffer, ResponseDelivery delivery) {
36 | delivery.onMessage(byteBuffer, null);
37 | }
38 |
39 | @Override
40 | public void onPing(Framedata framedata, ResponseDelivery delivery) {
41 | delivery.onPing(framedata);
42 | }
43 |
44 | @Override
45 | public void onPong(Framedata framedata, ResponseDelivery delivery) {
46 | delivery.onPong(framedata);
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/SimpleListener.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket;
2 |
3 | import com.zhangke.websocket.response.ErrorResponse;
4 |
5 | import org.java_websocket.framing.Framedata;
6 |
7 | import java.nio.ByteBuffer;
8 |
9 | /**
10 | * 一个简单的 WebSocket 监听器,实现了 {@link SocketListener} 接口,
11 | * 因为 SocketListener 中的方法比较多,所以在此提供了一个简单版本,
12 | * 只需要实现其中关注的方法即可。
13 | *
14 | * Created by ZhangKe on 2019/4/1.
15 | */
16 | public abstract class SimpleListener implements SocketListener {
17 |
18 | private final String TAG = "SimpleListener";
19 |
20 | @Override
21 | public void onConnected() {
22 | //to override
23 | }
24 |
25 | @Override
26 | public void onConnectFailed(Throwable e) {
27 | //to override
28 | }
29 |
30 | @Override
31 | public void onDisconnect() {
32 | //to override
33 | }
34 |
35 | @Override
36 | public void onMessage(String message, T data) {
37 | //to override
38 | }
39 |
40 | @Override
41 | public void onSendDataError(ErrorResponse errorResponse) {
42 | //to override
43 | }
44 |
45 | @Override
46 | public void onMessage(ByteBuffer bytes, T data) {
47 | //to override
48 | }
49 |
50 | @Override
51 | public void onPing(Framedata framedata) {
52 | //to override
53 | }
54 |
55 | @Override
56 | public void onPong(Framedata framedata) {
57 | //to override
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/SocketListener.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket;
2 |
3 | import com.zhangke.websocket.response.ErrorResponse;
4 |
5 | import org.java_websocket.framing.Framedata;
6 |
7 | import java.nio.ByteBuffer;
8 |
9 | /**
10 | * WebSocket 监听器,
11 | * for user
12 | * Created by ZhangKe on 2018/6/8.
13 | */
14 | public interface SocketListener {
15 |
16 | /**
17 | * 连接成功
18 | */
19 | void onConnected();
20 |
21 | /**
22 | * 连接失败
23 | */
24 | void onConnectFailed(Throwable e);
25 |
26 | /**
27 | * 连接断开
28 | */
29 | void onDisconnect();
30 |
31 | /**
32 | * 数据发送失败
33 | *
34 | * @param errorResponse 失败响应
35 | */
36 | void onSendDataError(ErrorResponse errorResponse);
37 |
38 | /**
39 | * 接收到文本消息
40 | *
41 | * @param message 文本消息
42 | * @param data 用户可将数据转成对应的泛型类型,可能为空,具体看用户在 {@link com.zhangke.websocket.dispatcher.IResponseDispatcher}
43 | * 中的实现,默认为空
44 | * @param IResponseDispatcher 中转换的泛型类型
45 | */
46 | void onMessage(String message, T data);
47 |
48 | /**
49 | * 接收到二进制消息
50 | *
51 | * @param bytes 二进制消息
52 | * @param data 用户可将数据转成对应的泛型类型,可能为空,具体看用户在 {@link com.zhangke.websocket.dispatcher.IResponseDispatcher}
53 | * 中的实现,默认为空
54 | * @param IResponseDispatcher 中转换的泛型类型
55 | */
56 | void onMessage(ByteBuffer bytes, T data);
57 |
58 | /**
59 | * 接收到 ping
60 | */
61 | void onPing(Framedata framedata);
62 |
63 | /**
64 | * 接收到 pong
65 | */
66 | void onPong(Framedata framedata);
67 | }
68 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/SocketWrapperListener.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket;
2 |
3 | import com.zhangke.websocket.request.Request;
4 | import com.zhangke.websocket.response.Response;
5 |
6 | /**
7 | * {@link WebSocketWrapper} 监听器
8 | *
9 | * Created by ZhangKe on 2019/3/22.
10 | */
11 | public interface SocketWrapperListener {
12 |
13 | /**
14 | * 连接成功
15 | */
16 | void onConnected();
17 |
18 | /**
19 | * 连接失败
20 | */
21 | void onConnectFailed(Throwable e);
22 |
23 | /**
24 | * 连接断开
25 | */
26 | void onDisconnect();
27 |
28 | /**
29 | * 数据发送失败
30 | *
31 | * @param request 发送的请求
32 | * @param type 失败类型:{@link com.zhangke.websocket.response.ErrorResponse#ERROR_NO_CONNECT} 未连接、
33 | * {@link com.zhangke.websocket.response.ErrorResponse#ERROR_UNKNOWN} 未知错误、
34 | * {@link com.zhangke.websocket.response.ErrorResponse#ERROR_UN_INIT} 初始化未完成
35 | */
36 | void onSendDataError(Request request, int type, Throwable tr);
37 |
38 | /**
39 | * 接收到消息
40 | */
41 | void onMessage(Response message);
42 | }
43 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/WebSocketEngine.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import android.os.Message;
6 |
7 | import com.zhangke.websocket.request.Request;
8 | import com.zhangke.websocket.response.ErrorResponse;
9 | import com.zhangke.websocket.util.LogUtil;
10 |
11 | import java.util.ArrayDeque;
12 | import java.util.Queue;
13 |
14 | /**
15 | * 使用操作线程发送数据
16 | *
17 | * Created by ZhangKe on 2019/3/29.
18 | */
19 | public class WebSocketEngine {
20 |
21 | private static final String TAG = "WSWebSocketEngine";
22 |
23 | private OptionThread mOptionThread;
24 |
25 | WebSocketEngine() {
26 | mOptionThread = new OptionThread();
27 | mOptionThread.start();
28 | }
29 |
30 | void sendRequest(WebSocketWrapper webSocket,
31 | Request request,
32 | SocketWrapperListener listener) {
33 | if (mOptionThread.mHandler == null) {
34 | listener.onSendDataError(request,
35 | ErrorResponse.ERROR_UN_INIT,
36 | null);
37 | } else {
38 | ReRunnable runnable = ReRunnable.obtain();
39 | runnable.type = 0;
40 | runnable.request = request;
41 | runnable.webSocketWrapper = webSocket;
42 | mOptionThread.mHandler.post(runnable);
43 | }
44 | }
45 |
46 | void connect(WebSocketWrapper webSocket,
47 | SocketWrapperListener listener) {
48 | if (mOptionThread.mHandler == null) {
49 | listener.onConnectFailed(new Exception("WebSocketEngine not start!"));
50 | }else{
51 | ReRunnable runnable = ReRunnable.obtain();
52 | runnable.type = 1;
53 | runnable.webSocketWrapper = webSocket;
54 | mOptionThread.mHandler.post(runnable);
55 | }
56 | }
57 |
58 | void disConnect(WebSocketWrapper webSocket,
59 | SocketWrapperListener listener) {
60 | if (mOptionThread.mHandler != null) {
61 | ReRunnable runnable = ReRunnable.obtain();
62 | runnable.type = 2;
63 | runnable.webSocketWrapper = webSocket;
64 | mOptionThread.mHandler.post(runnable);
65 | }else{
66 | LogUtil.e(TAG, "WebSocketEngine not start!");
67 | }
68 | }
69 |
70 | void destroyWebSocket(WebSocketWrapper webSocket){
71 | if (mOptionThread.mHandler != null) {
72 | ReRunnable runnable = ReRunnable.obtain();
73 | runnable.type = 3;
74 | runnable.webSocketWrapper = webSocket;
75 | mOptionThread.mHandler.post(runnable);
76 | }else{
77 | LogUtil.e(TAG, "WebSocketEngine not start!");
78 | }
79 | }
80 |
81 | public void destroy() {
82 | if (mOptionThread != null) {
83 | if (mOptionThread.mHandler != null) {
84 | mOptionThread.mHandler.sendEmptyMessage(OptionHandler.QUIT);
85 | }
86 | }
87 | }
88 |
89 | private class OptionThread extends Thread {
90 |
91 | private OptionHandler mHandler;
92 |
93 | @Override
94 | public void run() {
95 | super.run();
96 | Looper.prepare();
97 | mHandler = new OptionHandler();
98 | Looper.loop();
99 | }
100 | }
101 |
102 | private static class OptionHandler extends Handler {
103 |
104 | private static final int QUIT = 1;
105 |
106 | @Override
107 | public void handleMessage(Message msg) {
108 | super.handleMessage(msg);
109 | }
110 | }
111 |
112 | private static class ReRunnable implements Runnable {
113 |
114 | private static Queue POOL = new ArrayDeque<>(10);
115 |
116 | static ReRunnable obtain() {
117 | ReRunnable runnable = POOL.poll();
118 | if (runnable == null) {
119 | runnable = new ReRunnable();
120 | }
121 | return runnable;
122 | }
123 |
124 | /**
125 | * 0-发送数据;
126 | * 1-连接;
127 | * 2-断开连接;
128 | * 3-销毁 WebSocketWrapper 对象。
129 | */
130 | private int type;
131 | private WebSocketWrapper webSocketWrapper;
132 | private Request request;
133 |
134 | @Override
135 | public void run() {
136 | try {
137 | if (webSocketWrapper == null) return;
138 | if (type == 0 && request == null) return;
139 | if (type == 0) {
140 | webSocketWrapper.send(request);
141 | } else if (type == 1) {
142 | webSocketWrapper.reconnect();
143 | } else if (type == 2) {
144 | webSocketWrapper.disConnect();
145 | }else if(type == 3){
146 | webSocketWrapper.destroy();
147 | }
148 | } finally {
149 | webSocketWrapper = null;
150 | request = null;
151 | release();
152 | }
153 | }
154 |
155 | void release() {
156 | POOL.offer(this);
157 | }
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/dispatcher/DefaultResponseDispatcher.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket.dispatcher;
2 |
3 | import com.zhangke.websocket.response.ErrorResponse;
4 | import com.zhangke.websocket.response.Response;
5 |
6 | import org.java_websocket.framing.Framedata;
7 |
8 | import java.nio.ByteBuffer;
9 |
10 | /**
11 | * 通用消息调度器,没做任何数据处理
12 | * Created by ZhangKe on 2018/6/26.
13 | */
14 | public class DefaultResponseDispatcher implements IResponseDispatcher {
15 |
16 | @Override
17 | public void onConnected(ResponseDelivery delivery) {
18 | delivery.onConnected();
19 | }
20 |
21 | @Override
22 | public void onConnectFailed(Throwable cause, ResponseDelivery delivery) {
23 | delivery.onConnectFailed(cause);
24 | }
25 |
26 | @Override
27 | public void onDisconnect(ResponseDelivery delivery) {
28 | delivery.onDisconnect();
29 | }
30 |
31 | @Override
32 | public void onMessage(String message, ResponseDelivery delivery) {
33 | delivery.onMessage(message, null);
34 | }
35 |
36 | @Override
37 | public void onMessage(ByteBuffer byteBuffer, ResponseDelivery delivery) {
38 | delivery.onMessage(byteBuffer, null);
39 | }
40 |
41 | @Override
42 | public void onPing(Framedata framedata, ResponseDelivery delivery) {
43 | delivery.onPing(framedata);
44 | }
45 |
46 | @Override
47 | public void onPong(Framedata framedata, ResponseDelivery delivery) {
48 | delivery.onPong(framedata);
49 | }
50 |
51 | @Override
52 | public void onSendDataError(ErrorResponse error, ResponseDelivery delivery) {
53 | delivery.onSendDataError(error);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/dispatcher/EngineThread.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket.dispatcher;
2 |
3 | import android.os.Process;
4 |
5 | import com.zhangke.websocket.util.LogUtil;
6 |
7 | import java.util.concurrent.ArrayBlockingQueue;
8 | import java.util.concurrent.ExecutorService;
9 | import java.util.concurrent.Executors;
10 |
11 | /**
12 | * 用于处理接收到的数据的线程
13 | *
14 | * Created by ZhangKe on 2019/3/25.
15 | */
16 | public class EngineThread extends Thread {
17 |
18 | private String TAG = "WSEngineThread";
19 |
20 | private ArrayBlockingQueue jobQueue = new ArrayBlockingQueue<>(10);
21 |
22 | private ExecutorService executorService;
23 |
24 | private boolean stop;
25 |
26 | @Override
27 | public synchronized void start() {
28 | stop = false;
29 | super.start();
30 | }
31 |
32 | @Override
33 | public void run() {
34 | super.run();
35 | Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
36 | while (!stop) {
37 | try {
38 | ResponseProcessEngine.EngineEntity entity = jobQueue.take();
39 | if (entity.isError) {
40 | entity.dispatcher.onSendDataError(entity.errorResponse,
41 | entity.delivery);
42 | } else {
43 | entity.response.onResponse(entity.dispatcher, entity.delivery);
44 | }
45 | ResponseProcessEngine.EngineEntity.release(entity);
46 | } catch (InterruptedException e) {
47 | if (stop) {
48 | return;
49 | }
50 | } catch (Exception e) {
51 | LogUtil.e(TAG, "run()->Exception", e);
52 | }
53 | }
54 | }
55 |
56 | void add(final ResponseProcessEngine.EngineEntity entity) {
57 | if (!jobQueue.offer(entity)) {
58 | LogUtil.e(TAG, "Offer response to Engine failed!start an thread to put.");
59 | if (executorService == null) {
60 | executorService = Executors.newCachedThreadPool();
61 | }
62 | executorService.execute(new Runnable() {
63 | @Override
64 | public void run() {
65 | if (stop) {
66 | return;
67 | }
68 | try {
69 | jobQueue.put(entity);
70 | } catch (Exception e) {
71 | if (stop) {
72 | LogUtil.e(TAG, "put response failed!", e);
73 | } else {
74 | interrupt();
75 | }
76 | }
77 | }
78 | });
79 | }
80 | }
81 |
82 | /**
83 | * 结束线程
84 | */
85 | void quit() {
86 | stop = true;
87 | jobQueue.clear();
88 | EngineThread.this.interrupt();
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/dispatcher/IResponseDispatcher.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket.dispatcher;
2 |
3 | import com.zhangke.websocket.WebSocketSetting;
4 | import com.zhangke.websocket.request.FrameDataRequest;
5 | import com.zhangke.websocket.response.ErrorResponse;
6 | import com.zhangke.websocket.response.Response;
7 |
8 | import org.java_websocket.framing.Framedata;
9 |
10 | import java.nio.ByteBuffer;
11 |
12 | /**
13 | * 消息分发器,用于处理及分发接收到的消息的接口,
14 | * 如果需要自定义事件的分发,实现这个类并设置到{@link WebSocketSetting} 中即可。
15 | * Created by ZhangKe on 2018/6/26.
16 | */
17 | public interface IResponseDispatcher {
18 |
19 | /**
20 | * 连接成功
21 | */
22 | void onConnected(ResponseDelivery delivery);
23 |
24 | /**
25 | * 连接失败
26 | *
27 | * @param cause 失败原因
28 | */
29 | void onConnectFailed(Throwable cause, ResponseDelivery delivery);
30 |
31 | /**
32 | * 连接断开
33 | */
34 | void onDisconnect(ResponseDelivery delivery);
35 |
36 | /**
37 | * 接收到文本消息
38 | *
39 | * @param message 接收到的消息
40 | * @param delivery 消息发射器
41 | */
42 | void onMessage(String message, ResponseDelivery delivery);
43 |
44 | /**
45 | * 接收到二进制消息
46 | *
47 | * @param byteBuffer 接收到的消息
48 | * @param delivery 消息发射器
49 | */
50 | void onMessage(ByteBuffer byteBuffer, ResponseDelivery delivery);
51 |
52 | /**
53 | * 接收到 ping
54 | *
55 | * @param framedata 数据帧
56 | */
57 | void onPing(Framedata framedata, ResponseDelivery delivery);
58 |
59 | /**
60 | * 接收到 pong
61 | *
62 | * @param framedata 数据帧
63 | */
64 | void onPong(Framedata framedata, ResponseDelivery delivery);
65 |
66 | /**
67 | * 消息发送失败或接受到错误消息等等
68 | */
69 | void onSendDataError(ErrorResponse error, ResponseDelivery delivery);
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/dispatcher/ResponseDelivery.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket.dispatcher;
2 |
3 | import com.zhangke.websocket.SocketListener;
4 |
5 | /**
6 | * 消息发射器接口
7 | *
8 | * Created by ZhangKe on 2018/6/26.
9 | */
10 | public interface ResponseDelivery extends SocketListener {
11 |
12 | void addListener(SocketListener listener);
13 |
14 | void removeListener(SocketListener listener);
15 |
16 | void clear();
17 |
18 | boolean isEmpty();
19 | }
20 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/dispatcher/ResponseProcessEngine.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket.dispatcher;
2 |
3 | import com.zhangke.websocket.dispatcher.EngineThread;
4 | import com.zhangke.websocket.dispatcher.IResponseDispatcher;
5 | import com.zhangke.websocket.dispatcher.ResponseDelivery;
6 | import com.zhangke.websocket.response.ErrorResponse;
7 | import com.zhangke.websocket.response.Response;
8 |
9 | import java.util.ArrayDeque;
10 | import java.util.Queue;
11 |
12 | /**
13 | * 响应消息处理类
14 | *
15 | * Created by ZhangKe on 2019/3/25.
16 | */
17 | public class ResponseProcessEngine {
18 |
19 | private EngineThread mThread;
20 |
21 | public ResponseProcessEngine() {
22 | mThread = new EngineThread();
23 | mThread.start();
24 | }
25 |
26 | public void onMessageReceive(Response message,
27 | IResponseDispatcher dispatcher,
28 | ResponseDelivery delivery) {
29 | if (message == null || dispatcher == null || delivery == null) {
30 | return;
31 | }
32 | EngineEntity entity = EngineEntity.obtain();
33 | entity.dispatcher = dispatcher;
34 | entity.delivery = delivery;
35 | entity.isError = false;
36 | entity.response = message;
37 | entity.errorResponse = null;
38 | mThread.add(entity);
39 | }
40 |
41 | public void onSendDataError(ErrorResponse errorResponse,
42 | IResponseDispatcher dispatcher,
43 | ResponseDelivery delivery) {
44 | if (errorResponse == null || dispatcher == null || delivery == null) {
45 | return;
46 | }
47 | EngineEntity entity = EngineEntity.obtain();
48 | entity.dispatcher = dispatcher;
49 | entity.delivery = delivery;
50 | entity.isError = true;
51 | entity.errorResponse = errorResponse;
52 | entity.response = null;
53 | mThread.add(entity);
54 | }
55 |
56 | static class EngineEntity {
57 |
58 | private static Queue ENTITY_POOL = new ArrayDeque<>(10);
59 |
60 | boolean isError;
61 | Response response;
62 | ErrorResponse errorResponse;
63 | IResponseDispatcher dispatcher;
64 | ResponseDelivery delivery;
65 |
66 | static EngineEntity obtain() {
67 | EngineEntity engineEntity = ENTITY_POOL.poll();
68 | if (engineEntity == null) {
69 | engineEntity = new EngineEntity();
70 | }
71 | return engineEntity;
72 | }
73 |
74 | static void release(EngineEntity entity) {
75 | ENTITY_POOL.offer(entity);
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/request/ByteArrayRequest.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket.request;
2 |
3 | import org.java_websocket.client.WebSocketClient;
4 |
5 | /**
6 | * byte[] 类型的请求
7 | *
8 | * Created by ZhangKe on 2019/3/22.
9 | */
10 | public class ByteArrayRequest implements Request {
11 |
12 | ByteArrayRequest() {
13 | }
14 |
15 | private byte[] data;
16 |
17 | @Override
18 | public void setRequestData(byte[] data) {
19 | this.data = data;
20 | }
21 |
22 | @Override
23 | public byte[] getRequestData() {
24 | return this.data;
25 | }
26 |
27 | @Override
28 | public void send(WebSocketClient client) {
29 | client.send(this.data);
30 | }
31 |
32 | @Override
33 | public void release() {
34 | RequestFactory.releaseByteArrayRequest(this);
35 | }
36 |
37 | @Override
38 | public String toString() {
39 | return String.format("[@ByteArrayRequest%s,%s]",
40 | hashCode(),
41 | data == null ?
42 | "data:null" :
43 | "data.length:" + data.length);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/request/ByteBufferRequest.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket.request;
2 |
3 | import org.java_websocket.client.WebSocketClient;
4 |
5 | import java.nio.ByteBuffer;
6 |
7 | /**
8 | * ByteBuffer 类型的请求
9 | *
10 | * Created by ZhangKe on 2019/3/22.
11 | */
12 | public class ByteBufferRequest implements Request {
13 |
14 | private ByteBuffer data;
15 |
16 | ByteBufferRequest() {
17 | }
18 |
19 | @Override
20 | public void setRequestData(ByteBuffer data) {
21 | this.data = data;
22 | }
23 |
24 | @Override
25 | public ByteBuffer getRequestData() {
26 | return this.data;
27 | }
28 |
29 | @Override
30 | public void send(WebSocketClient client) {
31 | client.send(this.data);
32 | }
33 |
34 | @Override
35 | public void release() {
36 | RequestFactory.releaseByteBufferRequest(this);
37 | }
38 |
39 | @Override
40 | public String toString() {
41 | return String.format("[@ByteBufferRequest%s,ByteBuffer:%s]",
42 | hashCode(),
43 | data == null ?
44 | "null" :
45 | data.toString());
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/request/CollectionFrameDataRequest.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket.request;
2 |
3 | import org.java_websocket.client.WebSocketClient;
4 | import org.java_websocket.framing.Framedata;
5 |
6 | import java.util.Collection;
7 |
8 | /**
9 | * 发送 {@link Framedata} 集合
10 | *
11 | * Created by ZhangKe on 2019/3/28.
12 | */
13 | public class CollectionFrameDataRequest implements Request> {
14 |
15 | private Collection data;
16 |
17 | CollectionFrameDataRequest() {
18 | }
19 |
20 | @Override
21 | public void setRequestData(Collection data) {
22 | this.data = data;
23 | }
24 |
25 | @Override
26 | public Collection getRequestData() {
27 | return this.data;
28 | }
29 |
30 | @Override
31 | public void send(WebSocketClient client) {
32 | client.sendFrame(this.data);
33 | }
34 |
35 | @Override
36 | public void release() {
37 | RequestFactory.releaseCollectionFrameRequest(this);
38 | }
39 |
40 | @Override
41 | public String toString() {
42 | return String.format("[@CollectionFrameDataRequest%s,Collection:%s]",
43 | hashCode(),
44 | data == null ?
45 | "null" :
46 | data.size() + " length");
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/request/FrameDataRequest.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket.request;
2 |
3 | import org.java_websocket.client.WebSocketClient;
4 | import org.java_websocket.framing.Framedata;
5 |
6 | /**
7 | * 发送 {@link Framedata}
8 | *
9 | * Created by ZhangKe on 2019/3/28.
10 | */
11 | public class FrameDataRequest implements Request {
12 |
13 | private Framedata framedata;
14 |
15 | FrameDataRequest() {
16 | }
17 |
18 | @Override
19 | public void setRequestData(Framedata data) {
20 | this.framedata = data;
21 | }
22 |
23 | @Override
24 | public Framedata getRequestData() {
25 | return this.framedata;
26 | }
27 |
28 | @Override
29 | public void send(WebSocketClient client) {
30 | client.sendFrame(framedata);
31 | }
32 |
33 | @Override
34 | public void release() {
35 | RequestFactory.releaseFrameDataRequest(this);
36 | }
37 |
38 | @Override
39 | public String toString() {
40 | return String.format("[@FrameDataRequest%s,Framedata:%s]",
41 | hashCode(),
42 | framedata == null ?
43 | "null" :
44 | framedata.toString());
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/websocketlib/src/main/java/com/zhangke/websocket/request/PingRequest.java:
--------------------------------------------------------------------------------
1 | package com.zhangke.websocket.request;
2 |
3 | import org.java_websocket.client.WebSocketClient;
4 |
5 | /**
6 | * 发送 Ping
7 | *
8 | * Created by ZhangKe on 2019/3/28.
9 | */
10 | public class PingRequest implements Request