listener) {
238 | // this.applicationContextClient.registListener(NettyProcessorHandler.MESSAGE, listener);
239 | // }
240 |
241 | /**
242 | * 断开连接
243 | */
244 | public void disconnect(ChannelFuture channelFuture) throws Exception {
245 | if (channelFuture != null) {
246 | channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
247 | @Override
248 | public void operationComplete(ChannelFuture channelFuture) throws Exception {
249 | if (channelFuture != null) {
250 | connectState = CONNECT_CLOSED;
251 | if (!group.isShutdown() && !group.isShuttingDown()) {
252 | group.shutdownGracefully();// .sync();
253 | }
254 | // 已经关闭了 关闭心跳监控
255 | NettyAlarmManager.stopHeart();
256 | if (ApplicationContextClient.isClosed) {
257 | // 主动关闭行为
258 | // 关闭重新连接定时任务
259 | NettyAlarmManager.stopReconnection();
260 | Log.i(getClass().getName(), "stop netty server connection!" + channelFuture.channel().remoteAddress());
261 | } else {
262 | // 被动关闭行为
263 | // 连接关闭后启动重连
264 | NettyAlarmManager.startReconnection(mContext);
265 | Log.i(getClass().getName(), "netty server closed success!" + channelFuture.channel().remoteAddress());
266 | }
267 | }
268 | }
269 | });
270 | }
271 | }
272 |
273 | /**
274 | * 是否連接
275 | *
276 | * @return
277 | */
278 | public boolean isConnected() {
279 | return connectState == CONNECT_SUCCESS ? true : false;
280 | }
281 |
282 | /**
283 | * 是否連接正在进行中
284 | *
285 | * @return
286 | */
287 | public boolean isConnecting() {
288 | boolean b = false;
289 | switch (connectState) {
290 | case CONNECT_INIT:
291 | case CONNECT_PROCESSORING:
292 | b = true;
293 | break;
294 | default:
295 | break;
296 | }
297 | return b;
298 | }
299 |
300 | public static void main(String[] args) {
301 | try {
302 | new NettyServerManager(null, null).connect("127.0.0.1", 6319, null);
303 | } catch (Exception e) {
304 | // TODO Auto-generated catch block
305 | e.printStackTrace();
306 | }
307 | }
308 | }
309 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/src/com/netty/client/utils/Md5Util.java:
--------------------------------------------------------------------------------
1 | package com.netty.client.utils;
2 |
3 | /**
4 | *
5 | * Title:
6 | *
7 | *
8 | * Description: MD5数据加密
9 | *
10 | *
11 | * Copyright: Copyright (c) 2006
12 | *
13 | *
14 | * Company:
15 | *
16 | *
17 | * @author Tongzy
18 | * @version 1.0
19 | */
20 | public class Md5Util {
21 | /*
22 | * 下面这些S11-S44实际上是一个4*4的矩阵,在原始的C实现中是用#define 实现的, 这里把它们实现成为static
23 | * final是表示了只读,切能在同一个进程空间内的多个 Instance间共享
24 | */
25 | static final int S11 = 7;
26 | static final int S12 = 12;
27 | static final int S13 = 17;
28 | static final int S14 = 22;
29 |
30 | static final int S21 = 5;
31 | static final int S22 = 9;
32 | static final int S23 = 14;
33 | static final int S24 = 20;
34 |
35 | static final int S31 = 4;
36 | static final int S32 = 11;
37 | static final int S33 = 16;
38 | static final int S34 = 23;
39 |
40 | static final int S41 = 6;
41 | static final int S42 = 10;
42 | static final int S43 = 15;
43 | static final int S44 = 21;
44 |
45 | static final byte[] PADDING = { -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
46 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
47 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
48 | 0, 0, 0, 0, 0, 0, 0 };
49 | /*
50 | * 下面的三个成员是MD5计算过程中用到的3个核心数据,在原始的C实现中 被定义到MD5_CTX结构中
51 | *
52 | */
53 | private long[] state = new long[4]; // state (ABCD)
54 | private long[] count = new long[2]; // number of bits, modulo 2^64 (lsb
55 | // first)
56 | private byte[] buffer = new byte[64]; // input buffer
57 |
58 | /*
59 | * digestHexStr是MD5的唯一一个公共成员,是最新一次计算结果的 16进制ASCII表示.
60 | */
61 | public String digestHexStr;
62 |
63 | /*
64 | * digest,是最新一次计算结果的2进制内部表示,表示128bit的MD5值.
65 | */
66 | private byte[] digest = new byte[16];
67 |
68 | /*
69 | * getMD5ofStr是类MD5最主要的公共方法,入口参数是你想要进行MD5变换的字符串
70 | * 返回的是变换完的结果,这个结果是从公共成员digestHexStr取得的.
71 | */
72 | public String getMD5ofStr(String inbuf) {
73 | md5Init();
74 | md5Update(inbuf.getBytes(), inbuf.length());
75 | md5Final();
76 | digestHexStr = "";
77 | for (int i = 0; i < 16; i++) {
78 | digestHexStr += byteHEX(digest[i]);
79 | }
80 | return digestHexStr;
81 | }
82 |
83 | // 这是MD5这个类的标准构造函数,JavaBean要求有一个public的并且没有参数的构造函数
84 | public Md5Util() {
85 | md5Init();
86 | return;
87 | }
88 |
89 | /* md5Init是一个初始化函数,初始化核心变量,装入标准的幻数 */
90 | private void md5Init() {
91 | count[0] = 0L;
92 | count[1] = 0L;
93 | // /* Load magic initialization constants.
94 |
95 | state[0] = 0x67452301L;
96 | state[1] = 0xefcdab89L;
97 | state[2] = 0x98badcfeL;
98 | state[3] = 0x10325476L;
99 |
100 | return;
101 | }
102 |
103 | /*
104 | * F, G, H ,I 是4个基本的MD5函数,在原始的MD5的C实现中,由于它们是
105 | * 简单的位运算,可能出于效率的考虑把它们实现成了宏,在java中,我们把它们 实现成了private方法,名字保持了原来C中的。
106 | */
107 |
108 | private long F(long x, long y, long z) {
109 | return (x & y) | ((~x) & z);
110 |
111 | }
112 |
113 | private long G(long x, long y, long z) {
114 | return (x & z) | (y & (~z));
115 |
116 | }
117 |
118 | private long H(long x, long y, long z) {
119 | return x ^ y ^ z;
120 | }
121 |
122 | private long I(long x, long y, long z) {
123 | return y ^ (x | (~z));
124 | }
125 |
126 | /*
127 | * FF,GG,HH和II将调用F,G,H,I进行近一步变换 FF, GG, HH, and II transformations for
128 | * rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent
129 | * recomputation.
130 | */
131 |
132 | private long FF(long a, long b, long c, long d, long x, long s, long ac) {
133 | a += F(b, c, d) + x + ac;
134 | a = ((int) a << s) | ((int) a >>> (32 - s));
135 | a += b;
136 | return a;
137 | }
138 |
139 | private long GG(long a, long b, long c, long d, long x, long s, long ac) {
140 | a += G(b, c, d) + x + ac;
141 | a = ((int) a << s) | ((int) a >>> (32 - s));
142 | a += b;
143 | return a;
144 | }
145 |
146 | private long HH(long a, long b, long c, long d, long x, long s, long ac) {
147 | a += H(b, c, d) + x + ac;
148 | a = ((int) a << s) | ((int) a >>> (32 - s));
149 | a += b;
150 | return a;
151 | }
152 |
153 | private long II(long a, long b, long c, long d, long x, long s, long ac) {
154 | a += I(b, c, d) + x + ac;
155 | a = ((int) a << s) | ((int) a >>> (32 - s));
156 | a += b;
157 | return a;
158 | }
159 |
160 | /*
161 | * md5Update是MD5的主计算过程,inbuf是要变换的字节串,inputlen是长度,这个
162 | * 函数由getMD5ofStr调用,调用之前需要调用md5init,因此把它设计成private的
163 | */
164 | private void md5Update(byte[] inbuf, int inputLen) {
165 |
166 | int i, index, partLen;
167 | byte[] block = new byte[64];
168 | index = (int) (count[0] >>> 3) & 0x3F;
169 | // /* Update number of bits */
170 | if ((count[0] += (inputLen << 3)) < (inputLen << 3)) {
171 | count[1]++;
172 | }
173 | count[1] += (inputLen >>> 29);
174 |
175 | partLen = 64 - index;
176 |
177 | // Transform as many times as possible.
178 | if (inputLen >= partLen) {
179 | md5Memcpy(buffer, inbuf, index, 0, partLen);
180 | md5Transform(buffer);
181 |
182 | for (i = partLen; i + 63 < inputLen; i += 64) {
183 |
184 | md5Memcpy(block, inbuf, 0, i, 64);
185 | md5Transform(block);
186 | }
187 | index = 0;
188 |
189 | } else {
190 |
191 | i = 0;
192 | }
193 |
194 | // /* Buffer remaining input */
195 | md5Memcpy(buffer, inbuf, index, i, inputLen - i);
196 |
197 | }
198 |
199 | /*
200 | * md5Final整理和填写输出结果
201 | */
202 | private void md5Final() {
203 | byte[] bits = new byte[8];
204 | int index, padLen;
205 |
206 | // /* Save number of bits */
207 | Encode(bits, count, 8);
208 |
209 | // /* Pad out to 56 mod 64.
210 | index = (int) (count[0] >>> 3) & 0x3f;
211 | padLen = (index < 56) ? (56 - index) : (120 - index);
212 | md5Update(PADDING, padLen);
213 |
214 | // /* Append length (before padding) */
215 | md5Update(bits, 8);
216 |
217 | // /* Store state in digest */
218 | Encode(digest, state, 16);
219 |
220 | }
221 |
222 | /*
223 | * md5Memcpy是一个内部使用的byte数组的块拷贝函数,从input的inpos开始把len长度的
224 | * 字节拷贝到output的outpos位置开始
225 | */
226 |
227 | private void md5Memcpy(byte[] output, byte[] input, int outpos, int inpos,
228 | int len) {
229 | int i;
230 |
231 | for (i = 0; i < len; i++) {
232 | output[outpos + i] = input[inpos + i];
233 | }
234 | }
235 |
236 | /*
237 | * md5Transform是MD5核心变换程序,有md5Update调用,block是分块的原始字节
238 | */
239 | private void md5Transform(byte block[]) {
240 | long a = state[0], b = state[1], c = state[2], d = state[3];
241 | long[] x = new long[16];
242 |
243 | Decode(x, block, 64);
244 |
245 | /* Round 1 */
246 | a = FF(a, b, c, d, x[0], S11, 0xd76aa478L); /* 1 */
247 | d = FF(d, a, b, c, x[1], S12, 0xe8c7b756L); /* 2 */
248 | c = FF(c, d, a, b, x[2], S13, 0x242070dbL); /* 3 */
249 | b = FF(b, c, d, a, x[3], S14, 0xc1bdceeeL); /* 4 */
250 | a = FF(a, b, c, d, x[4], S11, 0xf57c0fafL); /* 5 */
251 | d = FF(d, a, b, c, x[5], S12, 0x4787c62aL); /* 6 */
252 | c = FF(c, d, a, b, x[6], S13, 0xa8304613L); /* 7 */
253 | b = FF(b, c, d, a, x[7], S14, 0xfd469501L); /* 8 */
254 | a = FF(a, b, c, d, x[8], S11, 0x698098d8L); /* 9 */
255 | d = FF(d, a, b, c, x[9], S12, 0x8b44f7afL); /* 10 */
256 | c = FF(c, d, a, b, x[10], S13, 0xffff5bb1L); /* 11 */
257 | b = FF(b, c, d, a, x[11], S14, 0x895cd7beL); /* 12 */
258 | a = FF(a, b, c, d, x[12], S11, 0x6b901122L); /* 13 */
259 | d = FF(d, a, b, c, x[13], S12, 0xfd987193L); /* 14 */
260 | c = FF(c, d, a, b, x[14], S13, 0xa679438eL); /* 15 */
261 | b = FF(b, c, d, a, x[15], S14, 0x49b40821L); /* 16 */
262 |
263 | /* Round 2 */
264 | a = GG(a, b, c, d, x[1], S21, 0xf61e2562L); /* 17 */
265 | d = GG(d, a, b, c, x[6], S22, 0xc040b340L); /* 18 */
266 | c = GG(c, d, a, b, x[11], S23, 0x265e5a51L); /* 19 */
267 | b = GG(b, c, d, a, x[0], S24, 0xe9b6c7aaL); /* 20 */
268 | a = GG(a, b, c, d, x[5], S21, 0xd62f105dL); /* 21 */
269 | d = GG(d, a, b, c, x[10], S22, 0x2441453L); /* 22 */
270 | c = GG(c, d, a, b, x[15], S23, 0xd8a1e681L); /* 23 */
271 | b = GG(b, c, d, a, x[4], S24, 0xe7d3fbc8L); /* 24 */
272 | a = GG(a, b, c, d, x[9], S21, 0x21e1cde6L); /* 25 */
273 | d = GG(d, a, b, c, x[14], S22, 0xc33707d6L); /* 26 */
274 | c = GG(c, d, a, b, x[3], S23, 0xf4d50d87L); /* 27 */
275 | b = GG(b, c, d, a, x[8], S24, 0x455a14edL); /* 28 */
276 | a = GG(a, b, c, d, x[13], S21, 0xa9e3e905L); /* 29 */
277 | d = GG(d, a, b, c, x[2], S22, 0xfcefa3f8L); /* 30 */
278 | c = GG(c, d, a, b, x[7], S23, 0x676f02d9L); /* 31 */
279 | b = GG(b, c, d, a, x[12], S24, 0x8d2a4c8aL); /* 32 */
280 |
281 | /* Round 3 */
282 | a = HH(a, b, c, d, x[5], S31, 0xfffa3942L); /* 33 */
283 | d = HH(d, a, b, c, x[8], S32, 0x8771f681L); /* 34 */
284 | c = HH(c, d, a, b, x[11], S33, 0x6d9d6122L); /* 35 */
285 | b = HH(b, c, d, a, x[14], S34, 0xfde5380cL); /* 36 */
286 | a = HH(a, b, c, d, x[1], S31, 0xa4beea44L); /* 37 */
287 | d = HH(d, a, b, c, x[4], S32, 0x4bdecfa9L); /* 38 */
288 | c = HH(c, d, a, b, x[7], S33, 0xf6bb4b60L); /* 39 */
289 | b = HH(b, c, d, a, x[10], S34, 0xbebfbc70L); /* 40 */
290 | a = HH(a, b, c, d, x[13], S31, 0x289b7ec6L); /* 41 */
291 | d = HH(d, a, b, c, x[0], S32, 0xeaa127faL); /* 42 */
292 | c = HH(c, d, a, b, x[3], S33, 0xd4ef3085L); /* 43 */
293 | b = HH(b, c, d, a, x[6], S34, 0x4881d05L); /* 44 */
294 | a = HH(a, b, c, d, x[9], S31, 0xd9d4d039L); /* 45 */
295 | d = HH(d, a, b, c, x[12], S32, 0xe6db99e5L); /* 46 */
296 | c = HH(c, d, a, b, x[15], S33, 0x1fa27cf8L); /* 47 */
297 | b = HH(b, c, d, a, x[2], S34, 0xc4ac5665L); /* 48 */
298 |
299 | /* Round 4 */
300 | a = II(a, b, c, d, x[0], S41, 0xf4292244L); /* 49 */
301 | d = II(d, a, b, c, x[7], S42, 0x432aff97L); /* 50 */
302 | c = II(c, d, a, b, x[14], S43, 0xab9423a7L); /* 51 */
303 | b = II(b, c, d, a, x[5], S44, 0xfc93a039L); /* 52 */
304 | a = II(a, b, c, d, x[12], S41, 0x655b59c3L); /* 53 */
305 | d = II(d, a, b, c, x[3], S42, 0x8f0ccc92L); /* 54 */
306 | c = II(c, d, a, b, x[10], S43, 0xffeff47dL); /* 55 */
307 | b = II(b, c, d, a, x[1], S44, 0x85845dd1L); /* 56 */
308 | a = II(a, b, c, d, x[8], S41, 0x6fa87e4fL); /* 57 */
309 | d = II(d, a, b, c, x[15], S42, 0xfe2ce6e0L); /* 58 */
310 | c = II(c, d, a, b, x[6], S43, 0xa3014314L); /* 59 */
311 | b = II(b, c, d, a, x[13], S44, 0x4e0811a1L); /* 60 */
312 | a = II(a, b, c, d, x[4], S41, 0xf7537e82L); /* 61 */
313 | d = II(d, a, b, c, x[11], S42, 0xbd3af235L); /* 62 */
314 | c = II(c, d, a, b, x[2], S43, 0x2ad7d2bbL); /* 63 */
315 | b = II(b, c, d, a, x[9], S44, 0xeb86d391L); /* 64 */
316 |
317 | state[0] += a;
318 | state[1] += b;
319 | state[2] += c;
320 | state[3] += d;
321 |
322 | }
323 |
324 | /*
325 | * Encode把long数组按顺序拆成byte数组,因为java的long类型是64bit的, 只拆低32bit,以适应原始C实现的用途
326 | */
327 | private void Encode(byte[] output, long[] input, int len) {
328 | int i, j;
329 |
330 | for (i = 0, j = 0; j < len; i++, j += 4) {
331 | output[j] = (byte) (input[i] & 0xffL);
332 | output[j + 1] = (byte) ((input[i] >>> 8) & 0xffL);
333 | output[j + 2] = (byte) ((input[i] >>> 16) & 0xffL);
334 | output[j + 3] = (byte) ((input[i] >>> 24) & 0xffL);
335 | }
336 | }
337 |
338 | /*
339 | * Decode把byte数组按顺序合成成long数组,因为java的long类型是64bit的,
340 | * 只合成低32bit,高32bit清零,以适应原始C实现的用途
341 | */
342 | private void Decode(long[] output, byte[] input, int len) {
343 | int i, j;
344 |
345 | for (i = 0, j = 0; j < len; i++, j += 4) {
346 | output[i] = b2iu(input[j]) | (b2iu(input[j + 1]) << 8)
347 | | (b2iu(input[j + 2]) << 16) | (b2iu(input[j + 3]) << 24);
348 | }
349 |
350 | return;
351 | }
352 |
353 | /*
354 | * b2iu是我写的一个把byte按照不考虑正负号的原则的"升位"程序,因为java没有unsigned运算
355 | */
356 | public static long b2iu(byte b) {
357 | return b < 0 ? b & 0x7F + 128 : b;
358 | }
359 |
360 | /*
361 | * byteHEX(),用来把一个byte类型的数转换成十六进制的ASCII表示,
362 | * 因为java中的byte的toString无法实现这一点,我们又没有C语言中的 sprintf(outbuf,"%02X",ib)
363 | */
364 | public static String byteHEX(byte ib) {
365 | char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
366 | 'B', 'C', 'D', 'E', 'F' };
367 | char[] ob = new char[2];
368 | ob[0] = Digit[(ib >>> 4) & 0X0F];
369 | ob[1] = Digit[ib & 0X0F];
370 | String s = new String(ob);
371 | return s;
372 | }
373 |
374 | public static String toMD5(String source) {
375 | Md5Util md5 = new Md5Util();
376 | return md5.getMD5ofStr(source);
377 | }
378 |
379 | public static void main(String[] args) {
380 | String s = "13775362424HC19HTW02452" + System.currentTimeMillis();
381 |
382 | System.out.println(toMD5(s));
383 | System.out.println(toMD5(s).length());
384 | }
385 |
386 | }
387 |
--------------------------------------------------------------------------------
/src/com/netty/client/context/ApplicationContextClient.java:
--------------------------------------------------------------------------------
1 | package com.netty.client.context;
2 |
3 | import io.netty.channel.ChannelHandlerContext;
4 |
5 | import java.util.ArrayList;
6 | import java.util.HashMap;
7 | import java.util.Iterator;
8 | import java.util.List;
9 | import java.util.Map;
10 |
11 | import android.content.Context;
12 | import android.net.wifi.WifiInfo;
13 | import android.net.wifi.WifiManager;
14 | import android.telephony.TelephonyManager;
15 | import android.util.Log;
16 |
17 | import com.netty.client.android.dao.Device;
18 | import com.netty.client.android.handler.NettyProcessorHandler;
19 | import com.netty.client.android.listener.INettyHandlerListener;
20 | import com.netty.client.android.listener.RegistrationResultListener;
21 | import com.netty.client.android.service.PushDbService;
22 | import com.netty.client.consts.SystemConsts;
23 | import com.netty.client.utils.Md5Util;
24 | import com.xwtec.protoc.CommandProtoc;
25 |
26 | /**
27 | * 客户端调用
28 | *
29 | * @author maofw
30 | *
31 | */
32 | public class ApplicationContextClient {
33 |
34 | // 设备在线状态
35 | public static final int DEVICE_ONLINE = 1;
36 | public static final int DEVICE_OFFLINE = 0;
37 |
38 | // 是否关闭状态
39 | public static boolean isClosed = false;
40 | private ChannelHandlerContext ctx;
41 | private Map deviceInfos = new HashMap();
42 |
43 | // 保存handler 回调Listener
44 | @SuppressWarnings("rawtypes")
45 | private Map> nettyHandlerListeners = new HashMap>();
46 |
47 | private PushDbService pushDbService;
48 | private Context mContext;
49 |
50 | public ApplicationContextClient(Context context) {
51 | this.mContext = context;
52 | this.pushDbService = PushDbService.getInstance(context);
53 | }
54 |
55 | public ChannelHandlerContext getCtx() {
56 | return ctx;
57 | }
58 |
59 | public void setCtx(ChannelHandlerContext ctx) {
60 | this.ctx = ctx;
61 | }
62 |
63 | public void writeAndFlush(CommandProtoc.PushMessage pushMessage) {
64 | if (this.ctx != null) {
65 | this.ctx.writeAndFlush(pushMessage);
66 | }
67 | }
68 |
69 | public Map getDeviceInfos() {
70 | if (deviceInfos == null || deviceInfos.isEmpty()) {
71 | Map map = this.pushDbService.queryDevicesForMap();
72 | if (map != null && map.size() > 0) {
73 | deviceInfos.putAll(map);
74 | }
75 | }
76 | return deviceInfos;
77 | }
78 |
79 | /**
80 | * 根据app包名获取设备信息
81 | *
82 | * @param appPackage
83 | * @return
84 | */
85 | public Device getDeviceInfoByAppPackage(String appPackage) {
86 | Map map = this.getDeviceInfos();
87 | if (map != null && !map.isEmpty()) {
88 | return map.get(appPackage);
89 | }
90 | return null;
91 | }
92 |
93 | /**
94 | * 註冊設備
95 | *
96 | * @param appKey
97 | * @param appPackage
98 | * @param deviceId
99 | * @param imei
100 | * @param regId
101 | * @return
102 | */
103 | public void saveOrUpdateDevice(Device device) {
104 | if (device != null) {
105 | deviceInfos.put(device.getAppPackage(), device);
106 | this.pushDbService.saveOrUpdateDevice(device);
107 | }
108 | }
109 |
110 | /**
111 | * 生成Device对象
112 | *
113 | * @param appKey
114 | * @param appPackage
115 | * @param deviceId
116 | * @param imei
117 | * @return
118 | */
119 |
120 | public Device makeDevice(Context context, String appKey, String appPackage) {
121 |
122 | Device deviceInfo = this.getDeviceInfoByAppPackage(appPackage);
123 | if (deviceInfo == null || (deviceInfo.getAppKey() != null && !deviceInfo.getAppKey().equals(appKey))) {
124 | TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
125 | String imei = tm.getDeviceId();
126 |
127 | String macAddress = null;
128 | WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
129 | WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
130 | if (null != info) {
131 | macAddress = info.getMacAddress();
132 | }
133 |
134 | String deviceId = Md5Util.toMD5(SystemConsts.CHANNEL + appKey + macAddress + imei);
135 | if (deviceInfo == null) {
136 | deviceInfo = new Device();
137 | }
138 | deviceInfo.setAppKey(appKey);
139 | deviceInfo.setAppPackage(appPackage);
140 | deviceInfo.setDeviceId(deviceId);
141 | deviceInfo.setImei(imei);
142 | deviceInfo.setIsOnline(DEVICE_OFFLINE);
143 | }
144 | return deviceInfo;
145 | }
146 |
147 | /**
148 | * 删除设备
149 | *
150 | * @param appPackage
151 | */
152 | public void deleteDeviceInfo(Device deviceInfo) {
153 | if (deviceInfo != null) {
154 | this.pushDbService.deleteDevice(deviceInfo);
155 | // 删除缓存内容
156 | deviceInfos.remove(deviceInfo.getAppPackage());
157 | }
158 | }
159 |
160 | public void offlineAllDevices() {
161 | if (deviceInfos != null && !deviceInfos.isEmpty()) {
162 | List list = new ArrayList();
163 | Iterator> iterator = deviceInfos.entrySet().iterator();
164 | while (iterator.hasNext()) {
165 | Map.Entry entry = iterator.next();
166 | Device device = entry.getValue();
167 | if (device != null) {
168 | device.setIsOnline(DEVICE_OFFLINE);
169 | list.add(device);
170 | }
171 | }
172 | this.pushDbService.saveOrUpdateDevices(list);
173 | list = null;
174 | }
175 |
176 | }
177 |
178 | @SuppressWarnings("rawtypes")
179 | public void registListener(String appPackage, Integer type, INettyHandlerListener listener) {
180 | if (listener != null) {
181 | Map mNettyHandlerListeners = nettyHandlerListeners.get(appPackage);
182 | INettyHandlerListener nettyHandlerListener = null;
183 | if (mNettyHandlerListeners == null) {
184 | mNettyHandlerListeners = new HashMap();
185 | nettyHandlerListeners.put(appPackage, mNettyHandlerListeners);
186 | } else {
187 | nettyHandlerListener = mNettyHandlerListeners.get(type);
188 | if (nettyHandlerListener != null) {
189 | nettyHandlerListener = null;
190 | }
191 | }
192 | mNettyHandlerListeners.put(type, listener);
193 | }
194 | }
195 |
196 | @SuppressWarnings("rawtypes")
197 | public INettyHandlerListener getNettyHandlerListener(String appPackage, Integer type) {
198 | if (appPackage != null && type != null && nettyHandlerListeners.containsKey(appPackage)) {
199 | Map mNettyHandlerListeners = nettyHandlerListeners.get(appPackage);
200 | INettyHandlerListener nettyHandlerListener = mNettyHandlerListeners == null ? null : mNettyHandlerListeners.get(type);
201 | return nettyHandlerListener;
202 | }
203 | return null;
204 | }
205 |
206 | /**
207 | * 心跳请求
208 | *
209 | * @param listener
210 | */
211 | public void sendHeartBeatMessage() {
212 | try {
213 | Log.i(ApplicationContextClient.class.getName(), "sendHeartBeatMessage");
214 | } catch (Exception e) {
215 | System.out.println("sendHeartBeatMessage");
216 | }
217 | if (ctx != null) {
218 | // 心跳请求
219 | CommandProtoc.PushMessage.Builder builder = this.createCommandPushMessage(CommandProtoc.PushMessage.Type.HEART_BEAT);
220 | ctx.writeAndFlush(builder.build());
221 | }
222 | }
223 |
224 | /**
225 | * 设备注册请求
226 | *
227 | * @param ctx
228 | * @param imei
229 | * @param deviceId
230 | * @param appKey
231 | * @param appPackage
232 | */
233 | public void sendRegistrationMessage(Device deviceInfo, INettyHandlerListener listener) {
234 | try {
235 | Log.i(ApplicationContextClient.class.getName(), "sendRegistrationMessage");
236 | } catch (Exception e) {
237 | System.out.println("sendRegistrationMessage");
238 | }
239 | // Log.i(ApplicationContextClient.class.getName(),"sendRegistrationMessage");
240 | // 激活后发送设备注册请求
241 | if (deviceInfo != null) {
242 | if (listener == null && this.getNettyHandlerListener(deviceInfo.getAppPackage(), NettyProcessorHandler.REGISTRATION_RESULT) == null) {
243 | this.registListener(deviceInfo.getAppPackage(), NettyProcessorHandler.REGISTRATION_RESULT, new RegistrationResultListener(mContext, deviceInfo));
244 | } else {
245 | this.registListener(deviceInfo.getAppPackage(), NettyProcessorHandler.REGISTRATION_RESULT, listener);
246 | }
247 | CommandProtoc.PushMessage pushMessage = this.createCommandRegistration(deviceInfo.getImei(), deviceInfo.getDeviceId(), deviceInfo.getAppKey(),
248 | deviceInfo.getAppPackage());
249 | ctx.writeAndFlush(pushMessage);
250 | }
251 | }
252 |
253 | /**
254 | * 发送设备上线消息
255 | *
256 | * @param ctx
257 | * @param deviceId
258 | */
259 | public void sendDeviceOnlineMessage(Device deviceInfo, INettyHandlerListener listener) {
260 | try {
261 | Log.i(ApplicationContextClient.class.getName(), "sendDeviceOnlineMessage");
262 | } catch (Exception e) {
263 | System.out.println("sendDeviceOnlineMessage");
264 | }
265 | if (deviceInfo != null) {
266 | this.registListener(deviceInfo.getAppPackage(), NettyProcessorHandler.DEVICE_ONLINE_RESULT, listener);
267 | CommandProtoc.PushMessage pushMessage = this.createCommandDeviceOnline(deviceInfo.getDeviceId());
268 | ctx.writeAndFlush(pushMessage);
269 | }
270 | }
271 |
272 | /**
273 | * 发送设备下线消息
274 | *
275 | * @param ctx
276 | * @param deviceId
277 | */
278 | public void sendDeviceOfflineMessage(Device deviceInfo, INettyHandlerListener listener) {
279 | try {
280 | Log.i(ApplicationContextClient.class.getName(), "sendDeviceOfflineMessage");
281 | } catch (Exception e) {
282 | System.out.println("sendDeviceOfflineMessage");
283 | }
284 | if (deviceInfo != null) {
285 | this.registListener(deviceInfo.getAppPackage(), NettyProcessorHandler.DEVICE_OFFLINE_RESULT, listener);
286 | CommandProtoc.PushMessage pushMessage = this.createCommandDeviceOffline(deviceInfo.getDeviceId());
287 | ctx.writeAndFlush(pushMessage);
288 | }
289 | }
290 |
291 | /**
292 | * 发送消息确认回执消息
293 | *
294 | * @param ctx
295 | * @param appKey
296 | * @param msgId
297 | */
298 | public void sendReceiptMessage(Device deviceInfo, String msgId) {
299 | try {
300 | Log.i(ApplicationContextClient.class.getName(), "sendReceiptMessage");
301 | } catch (Exception e) {
302 | System.out.println("sendReceiptMessage");
303 | }
304 | if (deviceInfo != null) {
305 | CommandProtoc.PushMessage pushMessage = this.createCommandMessageReceipt(deviceInfo.getAppKey(), deviceInfo.getRegId(), msgId);
306 | ctx.writeAndFlush(pushMessage);
307 | }
308 | }
309 |
310 | /**
311 | * 创建Registration对象
312 | *
313 | * @param type
314 | * @return
315 | */
316 | public CommandProtoc.PushMessage createCommandRegistration(String imei, String deviceId, String appKey, String appPackage) {
317 | CommandProtoc.Registration.Builder builder = CommandProtoc.Registration.newBuilder();
318 | builder.setImei(imei);
319 | builder.setDeviceId(deviceId);
320 | builder.setAppKey(appKey);
321 | builder.setAppPackage(appPackage);
322 | builder.setChannel(SystemConsts.CHANNEL);
323 | CommandProtoc.Registration commandProtoc = builder.build();
324 |
325 | // 创建消息对象
326 | CommandProtoc.PushMessage.Builder messageBuilder = this.createCommandPushMessage(CommandProtoc.PushMessage.Type.REGISTRATION);
327 | messageBuilder.setRegistration(commandProtoc);
328 | return messageBuilder.build();
329 | }
330 |
331 | /**
332 | * 创建DeviceOnline对象
333 | *
334 | * @param type
335 | * @return
336 | */
337 | public CommandProtoc.PushMessage createCommandDeviceOnline(String deviceId) {
338 | CommandProtoc.DeviceOnline.Builder builder = CommandProtoc.DeviceOnline.newBuilder();
339 | builder.setDeviceId(deviceId);
340 | CommandProtoc.DeviceOnline commandProtoc = builder.build();
341 |
342 | // 创建消息对象
343 | CommandProtoc.PushMessage.Builder messageBuilder = this.createCommandPushMessage(CommandProtoc.PushMessage.Type.DEVICE_ONLINE);
344 | messageBuilder.setDeviceOnline(commandProtoc);
345 | return messageBuilder.build();
346 | }
347 |
348 | /**
349 | * 创建DeviceOffline对象
350 | *
351 | * @param type
352 | * @return
353 | */
354 | public CommandProtoc.PushMessage createCommandDeviceOffline(String deviceId) {
355 | CommandProtoc.DeviceOffline.Builder builder = CommandProtoc.DeviceOffline.newBuilder();
356 | builder.setDeviceId(deviceId);
357 | CommandProtoc.DeviceOffline commandProtoc = builder.build();
358 |
359 | // 创建消息对象
360 | CommandProtoc.PushMessage.Builder messageBuilder = this.createCommandPushMessage(CommandProtoc.PushMessage.Type.DEVICE_OFFLINE);
361 | messageBuilder.setDeviceOffline(commandProtoc);
362 | return messageBuilder.build();
363 | }
364 |
365 | /**
366 | * 创建MessageReceipt对象
367 | *
368 | * @param type
369 | * @return
370 | */
371 | public CommandProtoc.PushMessage createCommandMessageReceipt(String appKey, String registrationId, String msgId) {
372 | CommandProtoc.MessageReceipt.Builder builder = CommandProtoc.MessageReceipt.newBuilder();
373 | builder.setAppKey(appKey);
374 | builder.setRegistrationId(registrationId);
375 | builder.setMsgId(msgId);
376 | CommandProtoc.MessageReceipt commandProtoc = builder.build();
377 | // 创建消息对象
378 | CommandProtoc.PushMessage.Builder messageBuilder = this.createCommandPushMessage(CommandProtoc.PushMessage.Type.MESSAGE_RECEIPT);
379 | messageBuilder.setMessageReceipt(commandProtoc);
380 | return messageBuilder.build();
381 | }
382 |
383 | /**
384 | * 创建发送消息对象
385 | *
386 | * @param type
387 | * @return
388 | */
389 | private CommandProtoc.PushMessage.Builder createCommandPushMessage(CommandProtoc.PushMessage.Type type) {
390 | CommandProtoc.PushMessage.Builder builder = CommandProtoc.PushMessage.newBuilder();
391 | builder.setType(type);
392 | return builder;
393 | }
394 |
395 | public void destory() {
396 | isClosed = true;
397 | if (this.deviceInfos != null) {
398 | this.deviceInfos.clear();
399 | this.deviceInfos = null;
400 | }
401 |
402 | if (nettyHandlerListeners != null) {
403 | nettyHandlerListeners.clear();
404 | nettyHandlerListeners = null;
405 | }
406 |
407 | pushDbService = null;
408 | if (ctx != null) {
409 | ctx.close();
410 | ctx = null;
411 | }
412 | }
413 | }
414 |
--------------------------------------------------------------------------------