├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── blanke │ │ └── xandroidsocket │ │ └── ApplicationTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── blanke │ │ │ └── xandroidsocket │ │ │ ├── MainActivity.java │ │ │ ├── TcpclientActivity.java │ │ │ ├── TcpserverActivity.java │ │ │ ├── TestActivity.java │ │ │ ├── UdpclientActivity.java │ │ │ ├── UdpserverActivity.java │ │ │ └── layout │ │ │ ├── ConsoleLayout.java │ │ │ └── StaticPackageLayout.java │ └── res │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── activity_tcpclient.xml │ │ ├── activity_tcpserver.xml │ │ ├── activity_test.xml │ │ ├── activity_udpclient.xml │ │ ├── activity_udpserver.xml │ │ ├── layout_console.xml │ │ └── layout_staticpackage.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── arrays.xml │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── blanke │ └── xandroidsocket │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── lib ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── blanke │ │ └── xsocket │ │ └── ApplicationTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── blanke │ │ │ └── xsocket │ │ │ ├── BaseXSocket.java │ │ │ ├── tcp │ │ │ ├── client │ │ │ │ ├── TcpConnConfig.java │ │ │ │ ├── XTcpClient.java │ │ │ │ ├── bean │ │ │ │ │ ├── TargetInfo.java │ │ │ │ │ └── TcpMsg.java │ │ │ │ ├── helper │ │ │ │ │ ├── decode │ │ │ │ │ │ ├── AbsDecodeHelper.java │ │ │ │ │ │ └── BaseDecodeHelper.java │ │ │ │ │ ├── stickpackage │ │ │ │ │ │ ├── AbsStickPackageHelper.java │ │ │ │ │ │ ├── BaseStickPackageHelper.java │ │ │ │ │ │ ├── SpecifiedStickPackageHelper.java │ │ │ │ │ │ ├── StaticLenStickPackageHelper.java │ │ │ │ │ │ └── VariableLenStickPackageHelper.java │ │ │ │ │ └── validation │ │ │ │ │ │ ├── AbsValidationHelper.java │ │ │ │ │ │ └── BaseValidationHelper.java │ │ │ │ ├── listener │ │ │ │ │ └── TcpClientListener.java │ │ │ │ ├── manager │ │ │ │ │ └── TcpClientManager.java │ │ │ │ └── state │ │ │ │ │ └── ClientState.java │ │ │ └── server │ │ │ │ ├── TcpServerConfig.java │ │ │ │ ├── XTcpServer.java │ │ │ │ ├── listener │ │ │ │ └── TcpServerListener.java │ │ │ │ ├── manager │ │ │ │ └── TcpServerManager.java │ │ │ │ └── state │ │ │ │ └── ServerState.java │ │ │ ├── udp │ │ │ └── client │ │ │ │ ├── UdpClientConfig.java │ │ │ │ ├── XUdp.java │ │ │ │ ├── bean │ │ │ │ └── UdpMsg.java │ │ │ │ ├── listener │ │ │ │ └── UdpClientListener.java │ │ │ │ └── manager │ │ │ │ └── UdpSocketManager.java │ │ │ └── utils │ │ │ ├── ByteUtils.java │ │ │ ├── CharsetUtil.java │ │ │ ├── ExceptionUtils.java │ │ │ ├── StringValidationUtils.java │ │ │ └── XSocketLog.java │ └── res │ │ └── values │ │ └── strings.xml │ └── test │ └── java │ └── com │ └── blanke │ └── xsocket │ └── ExampleUnitTest.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2012 Netflix, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # XAndroidSocket 2 | Socket封装,支持TCP/UDP客户端和服务端,支持自定义粘包处理、验证处理、解析处理。 3 | ##使用 4 | 详见目录[TCP/UDP使用demo](https://github.com/Blankeer/XAndroidSocket/tree/master/app/src/main/java/com/blanke/xandroidsocket) 5 | 下的例子,使用简单。 6 | 其中只有TCP才支持支持粘包处理、验证处理、解析处理。 7 | 8 | Step 1. Add the JitPack repository to your build file 9 | 10 | Add it in your root build.gradle at the end of repositories: 11 | 12 | allprojects { 13 | repositories { 14 | ... 15 | maven { url "https://jitpack.io" } 16 | } 17 | } 18 | Step 2. Add the dependency 19 | 20 | dependencies { 21 | compile 'com.github.Blankeer:XAndroidSocket:1.0.0' 22 | } 23 | 24 | ##粘包处理 25 | 提供的粘包处理有 26 | - [不处理](https://github.com/Blankeer/XAndroidSocket/blob/master/lib/src/main/java/com/blanke/xsocket/tcp/client/helper/stickpackage/BaseStickPackageHelper.java)(默认) 27 | - [首尾特殊字符处理](https://github.com/Blankeer/XAndroidSocket/blob/master/lib/src/main/java/com/blanke/xsocket/tcp/client/helper/stickpackage/SpecifiedStickPackageHelper.java) 28 | - [固定长度处理](https://github.com/Blankeer/XAndroidSocket/blob/master/lib/src/main/java/com/blanke/xsocket/tcp/client/helper/stickpackage/StaticLenStickPackageHelper.java) 29 | - [动态长度处理](https://github.com/Blankeer/XAndroidSocket/blob/master/lib/src/main/java/com/blanke/xsocket/tcp/client/helper/stickpackage/VariableLenStickPackageHelper.java) 30 | 31 | 支持自定义粘包处理,只需要实现[AbsStickPackageHelper](https://github.com/Blankeer/XAndroidSocket/blob/master/lib/src/main/java/com/blanke/xsocket/tcp/client/helper/stickpackage/AbsStickPackageHelper.java)接口, 32 | ```java 33 | /** 34 | * 接受消息,粘包处理的helper,通过inputstream,返回最终的数据,需手动处理粘包,返回的byte[]是我们预期的完整数据 35 | * note:这个方法会反复调用,直到解析到一条完整的数据。该方法是同步的,尽量不要做耗时操作,否则会阻塞读取数据 36 | */ 37 | public interface AbsStickPackageHelper { 38 | byte[] execute(InputStream is); 39 | } 40 | ``` 41 | 把接收消息的InputStream给你,你返回一个完整包的byte[]给我。 42 | ##验证处理 43 | 提供的验证处理是 [不处理](https://github.com/Blankeer/XAndroidSocket/blob/master/lib/src/main/java/com/blanke/xsocket/tcp/client/helper/validation/BaseValidationHelper.java),也是默认的。 44 | 自定义验证处理需要实现`AbsValidationHelper`: 45 | ```java 46 | public interface AbsValidationHelper { 47 | boolean execute(byte[] msg); 48 | } 49 | ``` 50 | 把完整的数据包给你,你需要返回是否验证通过,一般的自定义协议里都会有MD5验证,可以在这里验证。 51 | ##解析处理 52 | 提供的解析处理是 [不处理](https://github.com/Blankeer/XAndroidSocket/blob/master/lib/src/main/java/com/blanke/xsocket/tcp/client/helper/decode/BaseDecodeHelper.java),也是默认的。 53 | 自定义解析处理需要实现[AbsDecodeHelper](https://github.com/Blankeer/XAndroidSocket/blob/master/lib/src/main/java/com/blanke/xsocket/tcp/client/helper/decode/AbsDecodeHelper.java) 54 | ```java 55 | /** 56 | * 解析消息的处理 57 | */ 58 | public interface AbsDecodeHelper { 59 | /** 60 | * 61 | * @param data 完整的数据包 62 | * @param targetInfo 对方的信息(ip/port) 63 | * @param tcpConnConfig tcp连接配置,可自定义 64 | * @return 65 | */ 66 | byte[][] execute(byte[] data, TargetInfo targetInfo, TcpConnConfig tcpConnConfig); 67 | } 68 | ``` 69 | 设计思路:一般自定义协议会设计好多个字段组成,比如:`dataLen+data+type+md5`,数据长度+数据+类型+MD5,解析处理就是把这4个字段解析出来,返回byte[4][],便于后续处理。 70 | ## Log 71 | 日志开关:`XSocketLog.debug(true)` 72 | 73 | License 74 | ------- 75 | 76 | Licensed under the Apache License, Version 2.0 (the "License"); 77 | you may not use this file except in compliance with the License. 78 | You may obtain a copy of the License at 79 | 80 | http://www.apache.org/licenses/LICENSE-2.0 81 | 82 | Unless required by applicable law or agreed to in writing, software 83 | distributed under the License is distributed on an "AS IS" BASIS, 84 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 85 | See the License for the specific language governing permissions and 86 | limitations under the License. 87 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "23.0.3" 6 | 7 | defaultConfig { 8 | applicationId "com.blanke.xandroidsocket" 9 | minSdkVersion 14 10 | targetSdkVersion 23 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | testCompile 'junit:junit:4.12' 25 | compile project(':lib') 26 | compile 'com.android.support:appcompat-v7:23.4.0' 27 | compile 'com.android.support:design:23.4.0' 28 | } 29 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in C:\Users\asus\AppData\Local\Android\sdk1/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/blanke/xandroidsocket/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.blanke.xandroidsocket; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /app/src/main/java/com/blanke/xandroidsocket/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.blanke.xandroidsocket; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.util.Log; 7 | import android.view.View; 8 | 9 | import com.blanke.xsocket.tcp.client.TcpConnConfig; 10 | import com.blanke.xsocket.tcp.client.XTcpClient; 11 | import com.blanke.xsocket.tcp.client.bean.TargetInfo; 12 | import com.blanke.xsocket.tcp.client.bean.TcpMsg; 13 | import com.blanke.xsocket.tcp.client.helper.stickpackage.StaticLenStickPackageHelper; 14 | import com.blanke.xsocket.tcp.server.TcpServerConfig; 15 | import com.blanke.xsocket.tcp.server.XTcpServer; 16 | import com.blanke.xsocket.udp.client.XUdp; 17 | import com.blanke.xsocket.utils.XSocketLog; 18 | 19 | import java.util.Arrays; 20 | 21 | public class MainActivity extends AppCompatActivity { 22 | byte[] testGetToken = {(byte) -95, (byte) 15, (byte) 37, (byte) 0, (byte) 52, 23 | (byte) 52, (byte) 57, (byte) 49, (byte) 68, (byte) 66, (byte) 54, (byte) 48, (byte) 50, 24 | (byte) 67, (byte) 54, (byte) 53, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, 25 | (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, 26 | (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 76, (byte) 65, (byte) 50, (byte) 45, 27 | (byte) 83, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0}; 28 | 29 | private View layout; 30 | 31 | @Override 32 | protected void onCreate(Bundle savedInstanceState) { 33 | super.onCreate(savedInstanceState); 34 | setContentView(R.layout.activity_main); 35 | XSocketLog.debug(true); 36 | // tcpClientTest(); 37 | } 38 | 39 | private void start(Class activityClass) { 40 | startActivity(new Intent(this, activityClass)); 41 | } 42 | 43 | public void tcpclient(View v) { 44 | start(TcpclientActivity.class); 45 | // start(TestActivity.class); 46 | } 47 | 48 | public void tcpserver(View v) { 49 | start(TcpserverActivity.class); 50 | } 51 | 52 | public void udpclient(View v) { 53 | start(UdpclientActivity.class); 54 | } 55 | 56 | public void udpserver(View v) { 57 | start(UdpserverActivity.class); 58 | } 59 | 60 | private void tcpClientTest() { 61 | // UdpTargetInfo targetInfo = new UdpTargetInfo("192.168.88.1", 7682); 62 | TargetInfo targetInfo = new TargetInfo("10.155.1.221", 2222); 63 | XTcpClient xTcpClient = XTcpClient.getTcpClient(targetInfo); 64 | xTcpClient.config(new TcpConnConfig.Builder() 65 | .setConnTimeout(4000) 66 | // .setStickPackageHelper(new VariableLenStickPackageHelper(ByteOrder.LITTLE_ENDIAN, 2, 2, 4 + 8)) 67 | // .setStickPackageHelper(new SpecifiedStickPackageHelper("888".getBytes(), "999".getBytes())) 68 | .setStickPackageHelper(new StaticLenStickPackageHelper(3)) 69 | .setLocalPort(22223) 70 | .create()); 71 | // xTcpClient.addTcpClientListener(this); 72 | xTcpClient.connect(); 73 | } 74 | 75 | // private void udpClientTest() { 76 | //// UdpTargetInfo target = new UdpTargetInfo("10.155.1.221", 3333); 77 | // UdpTargetInfo target = new UdpTargetInfo("255.255.255.255", 9982); 78 | // XUdp xUdpClient = XUdp.getUdpClient(target); 79 | // xUdpClient.addUdpClientListener(this); 80 | // xUdpClient.setUdpClientConfig(new UdpClientConfig.Builder().setLocalPorrt(1234).create()); 81 | // byte[] suikongsearch = {(byte) 105, (byte) 112, (byte) -1, (byte) -1, (byte) -1, (byte) -1, (byte) -1, (byte) -1}; 82 | // xUdpClient.sendMsg(suikongsearch, true); 83 | // } 84 | 85 | private void tcpServerTest() { 86 | XTcpServer xTcpServer = XTcpServer.getTcpServer(4567); 87 | // xTcpServer.addTcpServerListener(this); 88 | TcpConnConfig clientConfig = new TcpConnConfig.Builder().setStickPackageHelper(new StaticLenStickPackageHelper(3)).create(); 89 | xTcpServer.config(new TcpServerConfig.Builder().setTcpConnConfig(clientConfig).create()); 90 | xTcpServer.startServer(); 91 | } 92 | 93 | //tcp client 94 | public void onConnected(XTcpClient client) { 95 | Log.e("xxx onConnected", "onConnected"); 96 | client.sendMsg(testGetToken); 97 | } 98 | 99 | public void onSended(XTcpClient client, TcpMsg tcpMsg) { 100 | 101 | } 102 | 103 | public void onDisconnected(XTcpClient client, String msg, Exception e) { 104 | Log.e("xxx onDisconnected", "onDisconnected " + msg + "," + e); 105 | } 106 | 107 | public void onReceive(XTcpClient client, TcpMsg tcpMsg) { 108 | 109 | } 110 | 111 | 112 | //udp 113 | 114 | public void onResponse(XUdp client, String msgs, byte[] sourceBytes) { 115 | Log.e("xxx onResponse", msgs + " " + Arrays.toString(sourceBytes)); 116 | 117 | } 118 | 119 | public void onReceive(XUdp client, String msg, Exception e) { 120 | 121 | } 122 | 123 | 124 | //tcp server 125 | public void onCreated(XTcpServer server) { 126 | Log.e("xxx XTcpServer", server + " created"); 127 | } 128 | 129 | public void onListened(XTcpServer server) { 130 | Log.e("xxx XTcpServer", server + " onListened"); 131 | } 132 | 133 | public void onAccept(XTcpServer server, XTcpClient tcpClient) { 134 | Log.e("xxx XTcpServer", " 收到客户端连接请求" + tcpClient); 135 | } 136 | 137 | public void onSended(XTcpServer server, XTcpClient tcpClient, TcpMsg tcpMsg) { 138 | 139 | } 140 | 141 | public void onReceive(XTcpServer server, XTcpClient tcpClient, TcpMsg tcpMsg) { 142 | 143 | } 144 | 145 | // @Override 146 | // public void onReceive(XTcpServer server, XTcpClient tcpClient, Object[] msgs, byte[] sourceBytes) { 147 | // Log.e("xxx XTcpServer", " 收到客户端的消息 " + tcpClient + " : " + msgs + "," + Arrays.toString(sourceBytes)); 148 | // tcpClient.sendMsg("hello " + tcpClient.getTargetInfo().getIp() + ",you msg=" + Arrays.toString(msgs)); 149 | // } 150 | 151 | public void onClientClosed(XTcpServer server, XTcpClient tcpClient, String msg, Exception e) { 152 | Log.e("xxx XTcpServer", " 客户端连接断开" + tcpClient + msg + e); 153 | } 154 | 155 | public void onServerClosed(XTcpServer server, String msg, Exception e) { 156 | Log.e("xxx XTcpServer", " tcpserver 关闭" + msg + e); 157 | } 158 | 159 | } 160 | -------------------------------------------------------------------------------- /app/src/main/java/com/blanke/xandroidsocket/TcpclientActivity.java: -------------------------------------------------------------------------------- 1 | package com.blanke.xandroidsocket; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.support.v7.widget.SwitchCompat; 6 | import android.view.View; 7 | import android.widget.Button; 8 | import android.widget.EditText; 9 | 10 | import com.blanke.xandroidsocket.layout.ConsoleLayout; 11 | import com.blanke.xandroidsocket.layout.StaticPackageLayout; 12 | import com.blanke.xsocket.tcp.client.TcpConnConfig; 13 | import com.blanke.xsocket.tcp.client.XTcpClient; 14 | import com.blanke.xsocket.tcp.client.bean.TargetInfo; 15 | import com.blanke.xsocket.tcp.client.bean.TcpMsg; 16 | import com.blanke.xsocket.tcp.client.helper.stickpackage.AbsStickPackageHelper; 17 | import com.blanke.xsocket.tcp.client.listener.TcpClientListener; 18 | import com.blanke.xsocket.utils.StringValidationUtils; 19 | 20 | import java.util.Arrays; 21 | 22 | public class TcpclientActivity extends AppCompatActivity implements View.OnClickListener, TcpClientListener { 23 | 24 | private Button tcpclientBuConnect; 25 | private EditText tcpclientEdit; 26 | private EditText tcpclientEditIp; 27 | private Button tcpclientBuSend; 28 | private StaticPackageLayout tcpclientStaticpackagelayout; 29 | private ConsoleLayout tcpclientConsole; 30 | private SwitchCompat tcpclientSwitchReconnect; 31 | private XTcpClient xTcpClient; 32 | 33 | @Override 34 | protected void onCreate(Bundle savedInstanceState) { 35 | super.onCreate(savedInstanceState); 36 | setContentView(R.layout.activity_tcpclient); 37 | tcpclientBuConnect = (Button) findViewById(R.id.tcpclient_bu_connect); 38 | tcpclientEdit = (EditText) findViewById(R.id.tcpclient_edit); 39 | tcpclientBuSend = (Button) findViewById(R.id.tcpclient_bu_send); 40 | tcpclientStaticpackagelayout = (StaticPackageLayout) findViewById(R.id.tcpclient_staticpackagelayout); 41 | tcpclientEditIp = (EditText) findViewById(R.id.tcpclient_edit_ip); 42 | tcpclientConsole = (ConsoleLayout) findViewById(R.id.tcpclient_console); 43 | tcpclientSwitchReconnect = (SwitchCompat) findViewById(R.id.tcpclient_switch_reconnect); 44 | tcpclientBuConnect.setOnClickListener(this); 45 | tcpclientBuSend.setOnClickListener(this); 46 | } 47 | 48 | @Override 49 | public void onClick(View v) { 50 | if (v.getId() == R.id.tcpclient_bu_connect) { 51 | tcpclientConsole.clearConsole(); 52 | if (xTcpClient != null && xTcpClient.isConnected()) { 53 | xTcpClient.disconnect(); 54 | } else { 55 | AbsStickPackageHelper stickHelper = tcpclientStaticpackagelayout.getStickPackageHelper(); 56 | if (stickHelper == null) { 57 | addMsg("粘包参数设置错误"); 58 | return; 59 | } 60 | String temp = tcpclientEditIp.getText().toString().trim(); 61 | String[] temp2 = temp.split(":"); 62 | if (temp2.length == 2 && StringValidationUtils.validateRegex(temp2[0], StringValidationUtils.RegexIP) 63 | && StringValidationUtils.validateRegex(temp2[1], StringValidationUtils.RegexPort)) { 64 | TargetInfo targetInfo = new TargetInfo(temp2[0], Integer.parseInt(temp2[1])); 65 | xTcpClient = XTcpClient.getTcpClient(targetInfo); 66 | xTcpClient.addTcpClientListener(this); 67 | xTcpClient.config(new TcpConnConfig.Builder() 68 | .setStickPackageHelper(stickHelper)//粘包 69 | .setIsReconnect(tcpclientSwitchReconnect.isChecked()) 70 | .create()); 71 | if (xTcpClient.isDisconnected()) { 72 | xTcpClient.connect(); 73 | } else { 74 | addMsg("已经存在该连接"); 75 | } 76 | } else { 77 | addMsg("服务器地址必须是 ip:port 形式"); 78 | } 79 | } 80 | } else {//send msg 81 | String text = tcpclientEdit.getText().toString().trim(); 82 | if (xTcpClient != null) { 83 | xTcpClient.sendMsg(text); 84 | } else { 85 | addMsg("还没有连接到服务器"); 86 | } 87 | } 88 | } 89 | 90 | @Override 91 | protected void onDestroy() { 92 | super.onDestroy(); 93 | if (xTcpClient != null) { 94 | xTcpClient.removeTcpClientListener(this); 95 | // xTcpClient.disconnect();//activity销毁时断开tcp连接 96 | } 97 | } 98 | 99 | private void addMsg(String msg) { 100 | this.tcpclientConsole.addLog(msg); 101 | } 102 | 103 | @Override 104 | public void onConnected(XTcpClient client) { 105 | addMsg(client.getTargetInfo().getIp() + "连接成功"); 106 | } 107 | 108 | @Override 109 | public void onSended(XTcpClient client, TcpMsg tcpMsg) { 110 | addMsg("我:" + tcpMsg.getSourceDataString()); 111 | } 112 | 113 | @Override 114 | public void onDisconnected(XTcpClient client, String msg, Exception e) { 115 | addMsg(client.getTargetInfo().getIp() + "断开连接 " + msg + e); 116 | } 117 | 118 | @Override 119 | public void onReceive(XTcpClient client, TcpMsg msg) { 120 | byte[][] res = msg.getEndDecodeData(); 121 | byte[] bytes = new byte[0]; 122 | for (byte[] i : res) { 123 | bytes = i; 124 | break; 125 | } 126 | addMsg(client.getTargetInfo().getIp() + ":" + " len= " + bytes.length + ", " 127 | + msg.getSourceDataString() + " bytes=" + Arrays.toString(bytes)); 128 | } 129 | 130 | @Override 131 | public void onValidationFail(XTcpClient client, TcpMsg tcpMsg) { 132 | 133 | } 134 | } 135 | 136 | -------------------------------------------------------------------------------- /app/src/main/java/com/blanke/xandroidsocket/TcpserverActivity.java: -------------------------------------------------------------------------------- 1 | package com.blanke.xandroidsocket; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.view.View; 6 | import android.widget.Button; 7 | import android.widget.EditText; 8 | 9 | import com.blanke.xandroidsocket.layout.ConsoleLayout; 10 | import com.blanke.xsocket.tcp.client.TcpConnConfig; 11 | import com.blanke.xsocket.tcp.client.XTcpClient; 12 | import com.blanke.xsocket.tcp.client.bean.TcpMsg; 13 | import com.blanke.xsocket.tcp.server.TcpServerConfig; 14 | import com.blanke.xsocket.tcp.server.XTcpServer; 15 | import com.blanke.xsocket.tcp.server.listener.TcpServerListener; 16 | import com.blanke.xsocket.utils.CharsetUtil; 17 | import com.blanke.xsocket.utils.StringValidationUtils; 18 | 19 | public class TcpserverActivity extends AppCompatActivity implements View.OnClickListener, TcpServerListener { 20 | private EditText tcpserverEditPort; 21 | private Button tcpserverBuConnect; 22 | private EditText tcpserverEdit; 23 | private Button tcpserverBuSend; 24 | private ConsoleLayout tcpserverConsole; 25 | private XTcpServer mXTcpServer; 26 | 27 | @Override 28 | protected void onCreate(Bundle savedInstanceState) { 29 | super.onCreate(savedInstanceState); 30 | setContentView(R.layout.activity_tcpserver); 31 | tcpserverEditPort = (EditText) findViewById(R.id.tcpserver_edit_port); 32 | tcpserverBuConnect = (Button) findViewById(R.id.tcpserver_bu_connect); 33 | tcpserverEdit = (EditText) findViewById(R.id.tcpserver_edit); 34 | tcpserverBuSend = (Button) findViewById(R.id.tcpserver_bu_send); 35 | tcpserverConsole = (ConsoleLayout) findViewById(R.id.tcpserver_console); 36 | 37 | tcpserverBuSend.setOnClickListener(this); 38 | tcpserverBuConnect.setOnClickListener(this); 39 | } 40 | 41 | @Override 42 | public void onClick(View v) { 43 | if (v.getId() == R.id.tcpserver_bu_connect) { 44 | tcpserverConsole.clearConsole(); 45 | if (mXTcpServer != null && mXTcpServer.isListening()) { 46 | mXTcpServer.stopServer(); 47 | } else { 48 | String port = tcpserverEditPort.getText().toString().trim(); 49 | if (StringValidationUtils.validateRegex(port, StringValidationUtils.RegexPort)) { 50 | if (mXTcpServer == null) { 51 | mXTcpServer = XTcpServer.getTcpServer(Integer.parseInt(port)); 52 | mXTcpServer.addTcpServerListener(this); 53 | mXTcpServer.config(new TcpServerConfig.Builder() 54 | .setTcpConnConfig(new TcpConnConfig.Builder().create()).create()); 55 | } 56 | mXTcpServer.startServer(); 57 | addMsg("tcp 服务开启 " + port); 58 | } else { 59 | addMsg("端口输入错误"); 60 | } 61 | } 62 | } else { 63 | String text = tcpserverEdit.getText().toString().trim(); 64 | if (mXTcpServer != null) { 65 | mXTcpServer.sendMsgToAll(text); 66 | } 67 | } 68 | } 69 | 70 | @Override 71 | protected void onDestroy() { 72 | super.onDestroy(); 73 | if (mXTcpServer != null) { 74 | mXTcpServer.removeTcpServerListener(this); 75 | // mXTcpServer.stopServer(); 76 | } 77 | } 78 | 79 | private void addMsg(String msg) { 80 | tcpserverConsole.addLog(msg); 81 | } 82 | 83 | 84 | @Override 85 | public void onCreated(XTcpServer server) { 86 | addMsg("服务启动成功"); 87 | } 88 | 89 | @Override 90 | public void onListened(XTcpServer server) { 91 | addMsg("服务listenling " + server.getPort()); 92 | } 93 | 94 | @Override 95 | public void onAccept(XTcpServer server, XTcpClient tcpClient) { 96 | addMsg("收到客户端连接请求 " + tcpClient.getTargetInfo().getIp()); 97 | } 98 | 99 | @Override 100 | public void onSended(XTcpServer server, XTcpClient tcpClient, TcpMsg tcpMsg) { 101 | addMsg("发送消息给 " + tcpClient.getTargetInfo().getIp() + " 成功 msg= " + tcpMsg.getSourceDataString()); 102 | } 103 | 104 | @Override 105 | public void onReceive(XTcpServer server, XTcpClient tcpClient, TcpMsg tcpMsg) { 106 | addMsg("收到客户端消息 " + tcpClient.getTargetInfo().getIp() + "," + CharsetUtil.dataToString(tcpMsg.getSourceDataBytes(), CharsetUtil.UTF_8)); 107 | } 108 | 109 | @Override 110 | public void onValidationFail(XTcpServer server, XTcpClient client, TcpMsg tcpMsg) { 111 | 112 | } 113 | 114 | @Override 115 | public void onClientClosed(XTcpServer server, XTcpClient tcpClient, String msg, Exception e) { 116 | addMsg("客户端连接断开 " + tcpClient.getTargetInfo().getIp() + msg + e); 117 | } 118 | 119 | @Override 120 | public void onServerClosed(XTcpServer server, String msg, Exception e) { 121 | addMsg("服务器关闭 " + server + msg + e); 122 | } 123 | } 124 | 125 | -------------------------------------------------------------------------------- /app/src/main/java/com/blanke/xandroidsocket/TestActivity.java: -------------------------------------------------------------------------------- 1 | package com.blanke.xandroidsocket; 2 | 3 | import android.support.v7.app.AppCompatActivity; 4 | import android.os.Bundle; 5 | 6 | public class TestActivity extends AppCompatActivity { 7 | 8 | @Override 9 | protected void onCreate(Bundle savedInstanceState) { 10 | super.onCreate(savedInstanceState); 11 | setContentView(R.layout.activity_test); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /app/src/main/java/com/blanke/xandroidsocket/UdpclientActivity.java: -------------------------------------------------------------------------------- 1 | package com.blanke.xandroidsocket; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.support.v7.widget.SwitchCompat; 6 | import android.view.View; 7 | import android.widget.Button; 8 | import android.widget.EditText; 9 | 10 | import com.blanke.xandroidsocket.layout.ConsoleLayout; 11 | import com.blanke.xsocket.tcp.client.bean.TargetInfo; 12 | import com.blanke.xsocket.tcp.client.bean.TcpMsg; 13 | import com.blanke.xsocket.udp.client.UdpClientConfig; 14 | import com.blanke.xsocket.udp.client.XUdp; 15 | import com.blanke.xsocket.udp.client.bean.UdpMsg; 16 | import com.blanke.xsocket.udp.client.listener.UdpClientListener; 17 | import com.blanke.xsocket.utils.StringValidationUtils; 18 | 19 | public class UdpclientActivity extends AppCompatActivity implements View.OnClickListener, UdpClientListener { 20 | private EditText udpclientEditIp; 21 | private EditText udpclientEdit; 22 | private Button udpclientBuSend; 23 | private XUdp mXUdp; 24 | private SwitchCompat udpclientSwitch; 25 | private ConsoleLayout tcpclientConsole; 26 | 27 | @Override 28 | protected void onCreate(Bundle savedInstanceState) { 29 | super.onCreate(savedInstanceState); 30 | setContentView(R.layout.activity_udpclient); 31 | 32 | udpclientEditIp = (EditText) findViewById(R.id.udpclient_edit_ip); 33 | udpclientEdit = (EditText) findViewById(R.id.udpclient_edit); 34 | udpclientBuSend = (Button) findViewById(R.id.udpclient_bu_send); 35 | udpclientSwitch = (SwitchCompat) findViewById(R.id.udpclient_switch); 36 | tcpclientConsole = (ConsoleLayout) findViewById(R.id.tcpclient_console); 37 | udpclientBuSend.setOnClickListener(this); 38 | } 39 | 40 | @Override 41 | protected void onDestroy() { 42 | super.onDestroy(); 43 | if (mXUdp != null) { 44 | mXUdp.removeUdpClientListener(this); 45 | mXUdp.stopUdpServer(); 46 | } 47 | } 48 | 49 | @Override 50 | public void onClick(View v) { 51 | String temp = udpclientEditIp.getText().toString().trim(); 52 | String[] temp2 = temp.split(":"); 53 | String text = udpclientEdit.getText().toString().trim(); 54 | TargetInfo targetInfo; 55 | if (temp2.length == 2 && StringValidationUtils.validateRegex(temp2[0], StringValidationUtils.RegexIP) 56 | && StringValidationUtils.validateRegex(temp2[1], StringValidationUtils.RegexPort)) { 57 | targetInfo = new TargetInfo(temp2[0], Integer.parseInt(temp2[1])); 58 | if (mXUdp == null) { 59 | mXUdp = XUdp.getUdpClient(); 60 | mXUdp.addUdpClientListener(this); 61 | } 62 | mXUdp.config(new UdpClientConfig.Builder() 63 | .setLocalPort(8989).create()); 64 | mXUdp.sendMsg(new UdpMsg(text, targetInfo, TcpMsg.MsgType.Send), udpclientSwitch.isChecked()); 65 | } else { 66 | addMsg("地址输入错误"); 67 | } 68 | } 69 | 70 | private void addMsg(String msg) { 71 | tcpclientConsole.addLog(msg); 72 | } 73 | 74 | @Override 75 | public void onStarted(XUdp XUdp) { 76 | 77 | 78 | } 79 | 80 | @Override 81 | public void onStoped(XUdp XUdp) { 82 | 83 | } 84 | 85 | @Override 86 | public void onSended(XUdp XUdp, UdpMsg udpMsg) { 87 | addMsg("我:" + udpMsg.getSourceDataString()); 88 | } 89 | 90 | @Override 91 | public void onReceive(XUdp client, UdpMsg msg) { 92 | addMsg("收到消息:" + msg.getSourceDataString()); 93 | } 94 | 95 | @Override 96 | public void onError(XUdp client, String msg, Exception e) { 97 | addMsg("onError:" + client + msg + e); 98 | } 99 | } 100 | 101 | -------------------------------------------------------------------------------- /app/src/main/java/com/blanke/xandroidsocket/UdpserverActivity.java: -------------------------------------------------------------------------------- 1 | package com.blanke.xandroidsocket; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.view.View; 6 | import android.widget.Button; 7 | import android.widget.EditText; 8 | 9 | import com.blanke.xandroidsocket.layout.ConsoleLayout; 10 | import com.blanke.xsocket.tcp.client.bean.TcpMsg; 11 | import com.blanke.xsocket.udp.client.UdpClientConfig; 12 | import com.blanke.xsocket.udp.client.XUdp; 13 | import com.blanke.xsocket.udp.client.bean.UdpMsg; 14 | import com.blanke.xsocket.udp.client.listener.UdpClientListener; 15 | import com.blanke.xsocket.utils.StringValidationUtils; 16 | 17 | public class UdpserverActivity extends AppCompatActivity implements View.OnClickListener, UdpClientListener { 18 | private EditText udpserverEditPort; 19 | private Button udpserverBuStart; 20 | private EditText udpserverEditAutoreply; 21 | private ConsoleLayout udpserverConsole; 22 | private XUdp mXUdp; 23 | 24 | @Override 25 | protected void onCreate(Bundle savedInstanceState) { 26 | super.onCreate(savedInstanceState); 27 | setContentView(R.layout.activity_udpserver); 28 | udpserverEditPort = (EditText) findViewById(R.id.udpserver_edit_port); 29 | udpserverBuStart = (Button) findViewById(R.id.udpserver_bu_start); 30 | udpserverEditAutoreply = (EditText) findViewById(R.id.udpserver_edit_autoreply); 31 | udpserverConsole = (ConsoleLayout) findViewById(R.id.udpserver_console); 32 | udpserverBuStart.setOnClickListener(this); 33 | } 34 | 35 | @Override 36 | public void onClick(View v) { 37 | if (v.getId() == R.id.udpserver_bu_start) { 38 | if (mXUdp != null && mXUdp.isUdpServerRuning()) { 39 | mXUdp.stopUdpServer(); 40 | } else { 41 | if (mXUdp == null) { 42 | String port = udpserverEditPort.getText().toString().trim(); 43 | mXUdp = XUdp.getUdpClient(); 44 | if (StringValidationUtils.validateRegex(port, StringValidationUtils.RegexPort)) { 45 | mXUdp.config(new UdpClientConfig.Builder().setLocalPort(Integer.parseInt(port)).create()); 46 | } 47 | mXUdp.addUdpClientListener(this); 48 | } 49 | mXUdp.startUdpServer(); 50 | } 51 | } 52 | } 53 | 54 | @Override 55 | protected void onDestroy() { 56 | super.onDestroy(); 57 | if (mXUdp != null) { 58 | mXUdp.removeUdpClientListener(this); 59 | mXUdp.stopUdpServer(); 60 | } 61 | } 62 | 63 | private void addMsg(String msg) { 64 | udpserverConsole.addLog(msg); 65 | } 66 | 67 | @Override 68 | public void onStarted(XUdp XUdp) { 69 | addMsg("udp服务开启"); 70 | } 71 | 72 | @Override 73 | public void onStoped(XUdp XUdp) { 74 | addMsg("udp服务关闭"); 75 | } 76 | 77 | @Override 78 | public void onSended(XUdp XUdp, UdpMsg udpMsg) { 79 | addMsg("我:" + udpMsg.getSourceDataString()); 80 | } 81 | 82 | @Override 83 | public void onReceive(XUdp client, UdpMsg msg) { 84 | addMsg("收到消息:" + msg.getSourceDataString()); 85 | String autoReply = udpserverEditAutoreply.getText().toString().trim(); 86 | client.sendMsg(new UdpMsg(autoReply, msg.getTarget(), TcpMsg.MsgType.Send)); 87 | } 88 | 89 | @Override 90 | public void onError(XUdp client, String msg, Exception e) { 91 | addMsg("onError:" + client + msg + e); 92 | } 93 | } 94 | 95 | -------------------------------------------------------------------------------- /app/src/main/java/com/blanke/xandroidsocket/layout/ConsoleLayout.java: -------------------------------------------------------------------------------- 1 | package com.blanke.xandroidsocket.layout; 2 | 3 | import android.annotation.TargetApi; 4 | import android.content.Context; 5 | import android.os.Build; 6 | import android.util.AttributeSet; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.widget.Button; 10 | import android.widget.FrameLayout; 11 | import android.widget.TextView; 12 | 13 | import com.blanke.xandroidsocket.R; 14 | 15 | /** 16 | */ 17 | public class ConsoleLayout extends FrameLayout { 18 | private TextView consoleTitle; 19 | private Button consoleClear; 20 | private TextView consoleText; 21 | 22 | 23 | public ConsoleLayout(Context context) { 24 | super(context); 25 | } 26 | 27 | public ConsoleLayout(Context context, AttributeSet attrs) { 28 | super(context, attrs); 29 | } 30 | 31 | public ConsoleLayout(Context context, AttributeSet attrs, int defStyleAttr) { 32 | super(context, attrs, defStyleAttr); 33 | } 34 | 35 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 36 | public ConsoleLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 37 | super(context, attrs, defStyleAttr, defStyleRes); 38 | } 39 | 40 | @Override 41 | protected void onFinishInflate() { 42 | super.onFinishInflate(); 43 | LayoutInflater.from(getContext()).inflate(R.layout.layout_console, this, true); 44 | consoleTitle = (TextView) findViewById(R.id.console_title); 45 | consoleClear = (Button) findViewById(R.id.console_clear); 46 | consoleText = (TextView) findViewById(R.id.console_text); 47 | consoleClear.setOnClickListener(new OnClickListener() { 48 | @Override 49 | public void onClick(View v) { 50 | clearConsole(); 51 | } 52 | }); 53 | } 54 | 55 | public void clearConsole() { 56 | consoleText.setText(""); 57 | } 58 | 59 | public void addLog(String msg) { 60 | consoleText.append(msg + "\n"); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /app/src/main/java/com/blanke/xandroidsocket/layout/StaticPackageLayout.java: -------------------------------------------------------------------------------- 1 | package com.blanke.xandroidsocket.layout; 2 | 3 | import android.annotation.TargetApi; 4 | import android.content.Context; 5 | import android.os.Build; 6 | import android.support.v7.widget.AppCompatSpinner; 7 | import android.text.TextUtils; 8 | import android.util.AttributeSet; 9 | import android.view.LayoutInflater; 10 | import android.view.View; 11 | import android.widget.AdapterView; 12 | import android.widget.EditText; 13 | import android.widget.FrameLayout; 14 | import android.widget.LinearLayout; 15 | 16 | import com.blanke.xandroidsocket.R; 17 | import com.blanke.xsocket.tcp.client.helper.stickpackage.AbsStickPackageHelper; 18 | import com.blanke.xsocket.tcp.client.helper.stickpackage.BaseStickPackageHelper; 19 | import com.blanke.xsocket.tcp.client.helper.stickpackage.SpecifiedStickPackageHelper; 20 | import com.blanke.xsocket.tcp.client.helper.stickpackage.StaticLenStickPackageHelper; 21 | import com.blanke.xsocket.tcp.client.helper.stickpackage.VariableLenStickPackageHelper; 22 | 23 | import java.nio.ByteOrder; 24 | 25 | /** 26 | */ 27 | public class StaticPackageLayout extends FrameLayout { 28 | private AppCompatSpinner staticpackageSpinnerChose; 29 | private EditText staticpackageEditStaticlen; 30 | private LinearLayout staticpackageLayoutVariablelen; 31 | private AppCompatSpinner staticpackageSpinnerOrder; 32 | private EditText staticpackageEditVariablelenLensize; 33 | private EditText staticpackageEditVariablelenLenindex; 34 | private EditText staticpackageEditVariablelenOffset; 35 | private LinearLayout staticpackageLayoutSpecified; 36 | private EditText staticpackageEditSpecifiedHead; 37 | private EditText staticpackageEditSpecifiedTail; 38 | private FrameLayout staticpackageLayout; 39 | private int selectPosition; 40 | 41 | public StaticPackageLayout(Context context) { 42 | super(context); 43 | } 44 | 45 | public StaticPackageLayout(Context context, AttributeSet attrs) { 46 | super(context, attrs); 47 | } 48 | 49 | public StaticPackageLayout(Context context, AttributeSet attrs, int defStyleAttr) { 50 | super(context, attrs, defStyleAttr); 51 | } 52 | 53 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 54 | public StaticPackageLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 55 | super(context, attrs, defStyleAttr, defStyleRes); 56 | } 57 | 58 | @Override 59 | protected void onFinishInflate() { 60 | super.onFinishInflate(); 61 | LayoutInflater.from(getContext()).inflate(R.layout.layout_staticpackage, this, true); 62 | staticpackageSpinnerChose = (AppCompatSpinner) findViewById(R.id.staticpackage_spinner_chose); 63 | staticpackageEditStaticlen = (EditText) findViewById(R.id.staticpackage_edit_staticlen); 64 | staticpackageLayoutVariablelen = (LinearLayout) findViewById(R.id.staticpackage_layout_variablelen); 65 | staticpackageSpinnerOrder = (AppCompatSpinner) findViewById(R.id.staticpackage_spinner_order); 66 | staticpackageEditVariablelenLensize = (EditText) findViewById(R.id.staticpackage_edit_variablelen_lensize); 67 | staticpackageEditVariablelenLenindex = (EditText) findViewById(R.id.staticpackage_edit_variablelen_lenindex); 68 | staticpackageEditVariablelenOffset = (EditText) findViewById(R.id.staticpackage_edit_variablelen_offset); 69 | staticpackageLayoutSpecified = (LinearLayout) findViewById(R.id.staticpackage_layout_specified); 70 | staticpackageEditSpecifiedHead = (EditText) findViewById(R.id.staticpackage_edit_specified_head); 71 | staticpackageEditSpecifiedTail = (EditText) findViewById(R.id.staticpackage_edit_specified_tail); 72 | staticpackageLayout = (FrameLayout) findViewById(R.id.staticpackage_layout); 73 | staticpackageSpinnerChose.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 74 | @Override 75 | public void onItemSelected(AdapterView parent, View view, int position, long id) { 76 | switch (position) { 77 | case 0: 78 | selectNone(); 79 | break; 80 | case 1: 81 | selectSpecified(); 82 | break; 83 | case 2: 84 | selectStaticlen(); 85 | break; 86 | case 3: 87 | selectVariablelen(); 88 | break; 89 | } 90 | selectPosition = position; 91 | } 92 | 93 | @Override 94 | public void onNothingSelected(AdapterView parent) { 95 | 96 | } 97 | }); 98 | 99 | } 100 | 101 | public AbsStickPackageHelper getStickPackageHelper() { 102 | AbsStickPackageHelper stickPackageHelper = null; 103 | switch (selectPosition) { 104 | case 0: 105 | selectNone(); 106 | stickPackageHelper = new BaseStickPackageHelper(); 107 | break; 108 | case 1: 109 | String head = staticpackageEditSpecifiedHead.getText().toString().trim(); 110 | String tail = staticpackageEditSpecifiedTail.getText().toString().trim(); 111 | if (!TextUtils.isEmpty(head) || !TextUtils.isEmpty(tail)) { 112 | stickPackageHelper = new SpecifiedStickPackageHelper(head.getBytes(), tail.getBytes()); 113 | } 114 | break; 115 | case 2: 116 | String lenStr = staticpackageEditStaticlen.getText().toString().trim(); 117 | if (!TextUtils.isEmpty(lenStr)) { 118 | int len = Integer.parseInt(lenStr); 119 | stickPackageHelper = new StaticLenStickPackageHelper(len); 120 | } 121 | break; 122 | case 3: 123 | int orderPosition = staticpackageSpinnerOrder.getSelectedItemPosition(); 124 | ByteOrder byteOrder = orderPosition == 0 ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; 125 | String lenSizeStr = staticpackageEditVariablelenLensize.getText().toString().trim(); 126 | if (!TextUtils.isEmpty(lenSizeStr)) { 127 | int lenSize = Integer.parseInt(lenSizeStr); 128 | String lenIndexStr = staticpackageEditVariablelenLenindex.getText().toString().trim(); 129 | if (!TextUtils.isEmpty(lenIndexStr)) { 130 | int lenIndex = Integer.parseInt(lenIndexStr); 131 | String lenOffsetStr = staticpackageEditVariablelenOffset.getText().toString().trim(); 132 | if (!TextUtils.isEmpty(lenOffsetStr)) { 133 | int offset = Integer.parseInt(lenOffsetStr); 134 | stickPackageHelper = new VariableLenStickPackageHelper(byteOrder, lenSize, lenIndex, offset); 135 | } 136 | } 137 | } 138 | break; 139 | } 140 | return stickPackageHelper; 141 | } 142 | 143 | private void selectNone() { 144 | hideAllChild(); 145 | } 146 | 147 | private void selectSpecified() { 148 | hideAllChild(); 149 | staticpackageLayoutSpecified.setVisibility(VISIBLE); 150 | } 151 | 152 | private void selectStaticlen() { 153 | hideAllChild(); 154 | staticpackageEditStaticlen.setVisibility(VISIBLE); 155 | } 156 | 157 | private void selectVariablelen() { 158 | hideAllChild(); 159 | staticpackageLayoutVariablelen.setVisibility(VISIBLE); 160 | } 161 | 162 | private void hideAllChild() { 163 | for (int i = 0; i < staticpackageLayout.getChildCount(); i++) { 164 | View v = staticpackageLayout.getChildAt(i); 165 | v.setVisibility(GONE); 166 | } 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 |