├── app ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ └── styles.xml │ │ │ ├── mipmap-hdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-anydpi-v26 │ │ │ │ ├── ic_launcher.xml │ │ │ │ └── ic_launcher_round.xml │ │ │ ├── layout │ │ │ │ └── activity_main.xml │ │ │ ├── drawable-v24 │ │ │ │ └── ic_launcher_foreground.xml │ │ │ └── drawable │ │ │ │ └── ic_launcher_background.xml │ │ ├── java │ │ │ └── com │ │ │ │ └── yun │ │ │ │ └── iconnection │ │ │ │ └── MainActivity.kt │ │ └── AndroidManifest.xml │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── yun │ │ │ └── iconnection │ │ │ └── ExampleUnitTest.kt │ └── androidTest │ │ └── java │ │ └── com │ │ └── yun │ │ └── iconnection │ │ └── ExampleInstrumentedTest.kt ├── proguard-rules.pro └── build.gradle ├── connection ├── .gitignore ├── consumer-rules.pro ├── src │ ├── main │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── com │ │ │ └── yun │ │ │ └── connection │ │ │ ├── model │ │ │ ├── ConnectionAgreement.java │ │ │ ├── ISendMessage.java │ │ │ └── IInitializeData.java │ │ │ ├── listener │ │ │ └── IConnectionListener.java │ │ │ ├── IConnectionService.java │ │ │ └── impl │ │ │ ├── NettyConnectionService.java │ │ │ └── NettyClientHandler.java │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── yun │ │ │ └── connection │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── yun │ │ └── connection │ │ └── ExampleInstrumentedTest.java ├── proguard-rules.pro └── build.gradle ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .idea ├── codeStyles │ ├── codeStyleConfig.xml │ └── Project.xml ├── misc.xml ├── runConfigurations.xml └── gradle.xml ├── .gitignore ├── gradle.properties ├── gradlew.bat ├── README.md └── gradlew /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /connection/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /connection/consumer-rules.pro: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name='IConnection' 2 | include ':app' 3 | include ':connection' 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | IConnection 3 | 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeyunHZ/IConnection/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeyunHZ/IConnection/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeyunHZ/IConnection/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeyunHZ/IConnection/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeyunHZ/IConnection/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeyunHZ/IConnection/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /connection/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeyunHZ/IConnection/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeyunHZ/IConnection/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeyunHZ/IConnection/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeyunHZ/IConnection/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yeyunHZ/IConnection/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #6200EE 4 | #3700B3 5 | #03DAC5 6 | 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Nov 18 09:51:54 CST 2020 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip 7 | -------------------------------------------------------------------------------- /connection/src/main/java/com/yun/connection/model/ConnectionAgreement.java: -------------------------------------------------------------------------------- 1 | package com.yun.connection.model; 2 | 3 | /** 4 | * 通讯协议 5 | */ 6 | public enum ConnectionAgreement { 7 | //string 8 | STRING, 9 | //json 10 | JSON, 11 | //protobuf 12 | PROTOBUF; 13 | } 14 | -------------------------------------------------------------------------------- /connection/src/main/java/com/yun/connection/model/ISendMessage.java: -------------------------------------------------------------------------------- 1 | package com.yun.connection.model; 2 | 3 | /** 4 | * 发送的数据模型 5 | */ 6 | public interface ISendMessage { 7 | /** 8 | * 获取消息 9 | * 10 | * @return 11 | */ 12 | public T getData(); 13 | } 14 | 15 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | -------------------------------------------------------------------------------- /app/src/main/java/com/yun/iconnection/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.yun.iconnection 2 | 3 | import androidx.appcompat.app.AppCompatActivity 4 | import android.os.Bundle 5 | 6 | class MainActivity : AppCompatActivity() { 7 | 8 | override fun onCreate(savedInstanceState: Bundle?) { 9 | super.onCreate(savedInstanceState) 10 | setContentView(R.layout.activity_main) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/yun/iconnection/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.yun.iconnection 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /connection/src/test/java/com/yun/connection/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.yun.connection; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /connection/src/main/java/com/yun/connection/model/IInitializeData.java: -------------------------------------------------------------------------------- 1 | package com.yun.connection.model; 2 | 3 | /** 4 | * 初始化数据 5 | */ 6 | public interface IInitializeData { 7 | /** 8 | * 获取协议 9 | * 10 | * @return 11 | */ 12 | public ConnectionAgreement getAgreement(); 13 | 14 | /** 15 | * 心跳内容 16 | * 17 | * @return 18 | */ 19 | public ISendMessage getHeartBeatMessage(); 20 | 21 | /** 22 | * 注册内容 23 | * 24 | * @return 25 | */ 26 | public ISendMessage getChannelActiveMessage(); 27 | 28 | /** 29 | * 协议内容类型 30 | * 31 | * @return 32 | */ 33 | public Object agreementMessageData(); 34 | 35 | } 36 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 20 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/yun/iconnection/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.yun.iconnection 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.yun.iconnection", appContext.packageName) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /connection/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 17 | 18 | -------------------------------------------------------------------------------- /connection/src/main/java/com/yun/connection/listener/IConnectionListener.java: -------------------------------------------------------------------------------- 1 | package com.yun.connection.listener; 2 | 3 | import com.yun.connection.model.ISendMessage; 4 | 5 | import java.lang.reflect.Type; 6 | 7 | /** 8 | * 长连接监听 9 | */ 10 | public interface IConnectionListener { 11 | /** 12 | * 连接 13 | */ 14 | public void onConnect(); 15 | 16 | /** 17 | * 断连 18 | */ 19 | public void onDisConnect(); 20 | 21 | /** 22 | * 接收到消息 23 | */ 24 | public Object onReceive(T data); 25 | 26 | /** 27 | * 重新连接 28 | */ 29 | public void onReConnect(); 30 | 31 | /** 32 | * 当接收的数据为json时 需要返回 33 | * 接收的数据类型 34 | * 35 | * @return 36 | */ 37 | public Type getMessageType(); 38 | 39 | 40 | /** 41 | * 发送消息 42 | * 43 | * @param sendMessage 44 | */ 45 | public void sendMessage(ISendMessage sendMessage); 46 | 47 | } 48 | -------------------------------------------------------------------------------- /connection/src/androidTest/java/com/yun/connection/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.yun.connection; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | 25 | assertEquals("com.yun.connection.test", appContext.getPackageName()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official 22 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-android-extensions' 4 | 5 | android { 6 | compileSdkVersion 30 7 | buildToolsVersion "30.0.2" 8 | 9 | defaultConfig { 10 | applicationId "com.yun.iconnection" 11 | minSdkVersion 19 12 | targetSdkVersion 30 13 | versionCode 1 14 | versionName "1.0" 15 | 16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 17 | } 18 | 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | 26 | } 27 | 28 | dependencies { 29 | implementation fileTree(dir: 'libs', include: ['*.jar']) 30 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 31 | implementation 'androidx.appcompat:appcompat:1.2.0' 32 | implementation 'androidx.core:core-ktx:1.3.2' 33 | implementation 'androidx.constraintlayout:constraintlayout:2.0.4' 34 | testImplementation 'junit:junit:4.12' 35 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 36 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' 37 | } 38 | -------------------------------------------------------------------------------- /connection/src/main/java/com/yun/connection/IConnectionService.java: -------------------------------------------------------------------------------- 1 | package com.yun.connection; 2 | 3 | import com.yun.connection.listener.IConnectionListener; 4 | import com.yun.connection.model.IInitializeData; 5 | import com.yun.connection.model.ISendMessage; 6 | 7 | /** 8 | * 长连接service 9 | */ 10 | public interface IConnectionService { 11 | /** 12 | * 创建长连接 13 | * 14 | * @param host 15 | * @param port 16 | * @param iInitializeData 17 | */ 18 | public void create(String host, int port, IInitializeData iInitializeData); 19 | 20 | 21 | /** 22 | * 添加监听 23 | * 24 | * @param iConnectionListener 25 | */ 26 | public void addListener(IConnectionListener iConnectionListener); 27 | 28 | 29 | /** 30 | * 移除监听 31 | * 32 | * @param iConnectionListener 33 | */ 34 | public void removeListener(IConnectionListener iConnectionListener); 35 | 36 | /** 37 | * 开始连接 38 | */ 39 | public void connect(); 40 | 41 | 42 | /** 43 | * 断开连接 44 | */ 45 | public void disConnect(); 46 | 47 | /** 48 | * 发送数据 49 | * 50 | * @param sendMessage 51 | * @param isNeedReTry 是否需要重连 52 | */ 53 | public void sendMessage(ISendMessage sendMessage, boolean isNeedReTry); 54 | 55 | /** 56 | * 是否已连接 57 | */ 58 | public boolean isConnect(); 59 | } 60 | -------------------------------------------------------------------------------- /connection/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 30 5 | buildToolsVersion "30.0.2" 6 | 7 | defaultConfig { 8 | minSdkVersion 19 9 | targetSdkVersion 30 10 | versionCode 1 11 | versionName "1.0" 12 | 13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 14 | consumerProguardFiles 'consumer-rules.pro' 15 | } 16 | 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | compileOptions { 24 | sourceCompatibility = 1.8 25 | targetCompatibility = 1.8 26 | } 27 | 28 | } 29 | 30 | dependencies { 31 | implementation fileTree(dir: 'libs', include: ['*.jar']) 32 | 33 | implementation 'androidx.appcompat:appcompat:1.2.0' 34 | testImplementation 'junit:junit:4.12' 35 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 36 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' 37 | implementation fileTree(dir: 'libs', include: ['*.jar']) 38 | implementation 'io.netty:netty-all:5.0.0.Alpha2' 39 | implementation 'com.google.code.gson:gson:2.8.5' 40 | api 'io.reactivex.rxjava2:rxandroid:2.1.1' 41 | api 'io.reactivex.rxjava2:rxjava:2.2.10' 42 | api 'com.google.protobuf:protobuf-java:3.8.0' 43 | api 'com.google.protobuf:protoc:3.7.0' 44 | } 45 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 简介 2 | === 3 | 4 | Android开发中我们经常需要使用到长连接来维持与服务器端的通讯,Connection提供了长连接的抽象类,以及一个基于netty的默认实现,支持多种通讯协议(String,Json,protobuf) 5 | 6 | 7 | 使用 8 | === 9 | 1、IConnectionService是长连接的抽象接口,提供了包括创建长连接、添加监听、发送心跳包等功能 10 | ```Java 11 | implementation 'com.yun:connection:1.2.0' 12 | ``` 13 | ```Java 14 | 15 | /** 16 | * 长连接service 17 | */ 18 | public interface IConnectionService { 19 | /** 20 | * 创建长连接 21 | * 22 | * @param host 23 | * @param port 24 | * @param iInitializeData 25 | */ 26 | public void create(String host, int port, IInitializeData iInitializeData); 27 | 28 | 29 | /** 30 | * 添加监听 31 | * 32 | * @param iConnectionListener 33 | */ 34 | public void addListener(IConnectionListener iConnectionListener); 35 | 36 | 37 | /** 38 | * 移除监听 39 | * 40 | * @param iConnectionListener 41 | */ 42 | public void removeListener(IConnectionListener iConnectionListener); 43 | 44 | /** 45 | * 开始连接 46 | */ 47 | public void connect(); 48 | 49 | 50 | /** 51 | * 断开连接 52 | */ 53 | public void disConnect(); 54 | 55 | /** 56 | * 发送数据 57 | * 58 | * @param sendMessage 59 | * @param isNeedReTry 是否需要重连 60 | */ 61 | public void sendMessage(ISendMessage sendMessage, boolean isNeedReTry); 62 | 63 | /** 64 | * 是否已连接 65 | */ 66 | public boolean isConnect(); 67 | } 68 | 69 | ``` 70 | 71 | 72 | 2、使用netty的实现类 73 | 例:使用protouf作为通讯协议 74 | ```Java 75 | IConnectionService iConnectionService = new NettyConnectionService(); 76 | IInitializeData iInitializeData = new IInitializeData() { 77 | @Override 78 | public ConnectionAgreement getAgreement() { 79 | //获取协议 80 | return ConnectionAgreement.PROTOBUF; 81 | } 82 | 83 | @Override 84 | public ISendMessage getHeartBeatMessage() { 85 | //心跳内容 86 | return new SendMessage(pingMsg); 87 | } 88 | 89 | @Override 90 | public ISendMessage getChannelActiveMessage() { 91 | //注册内容 92 | return new SendMessage(registerMsg); 93 | } 94 | 95 | @Override 96 | public Object agreementMessageData() { 97 | //协议内容类型 98 | return Response.getDefaultInstance(); 99 | } 100 | }; 101 | iConnectionService.create(AppConstant.TCP_ip, AppConstant.TCP_port, iInitializeData); 102 | iConnectionService.addListener(this); 103 | ``` 104 | 105 | ```Java 106 | 启动连接服务 107 | iConnectionService.connect(); 108 | ``` 109 | 110 | ```Java 111 | 关闭连接服务 112 | iConnectionService.disConnect(); 113 | ``` 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 8 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | xmlns:android 17 | 18 | ^$ 19 | 20 | 21 | 22 |
23 |
24 | 25 | 26 | 27 | xmlns:.* 28 | 29 | ^$ 30 | 31 | 32 | BY_NAME 33 | 34 |
35 |
36 | 37 | 38 | 39 | .*:id 40 | 41 | http://schemas.android.com/apk/res/android 42 | 43 | 44 | 45 |
46 |
47 | 48 | 49 | 50 | .*:name 51 | 52 | http://schemas.android.com/apk/res/android 53 | 54 | 55 | 56 |
57 |
58 | 59 | 60 | 61 | name 62 | 63 | ^$ 64 | 65 | 66 | 67 |
68 |
69 | 70 | 71 | 72 | style 73 | 74 | ^$ 75 | 76 | 77 | 78 |
79 |
80 | 81 | 82 | 83 | .* 84 | 85 | ^$ 86 | 87 | 88 | BY_NAME 89 | 90 |
91 |
92 | 93 | 94 | 95 | .* 96 | 97 | http://schemas.android.com/apk/res/android 98 | 99 | 100 | ANDROID_ATTRIBUTE_ORDER 101 | 102 |
103 |
104 | 105 | 106 | 107 | .* 108 | 109 | .* 110 | 111 | 112 | BY_NAME 113 | 114 |
115 |
116 |
117 |
118 | 119 | 121 |
122 |
-------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /connection/src/main/java/com/yun/connection/impl/NettyConnectionService.java: -------------------------------------------------------------------------------- 1 | package com.yun.connection.impl; 2 | 3 | import android.annotation.SuppressLint; 4 | 5 | import com.google.gson.Gson; 6 | import com.google.protobuf.MessageLite; 7 | import com.yun.connection.IConnectionService; 8 | import com.yun.connection.listener.IConnectionListener; 9 | import com.yun.connection.model.ConnectionAgreement; 10 | import com.yun.connection.model.IInitializeData; 11 | import com.yun.connection.model.ISendMessage; 12 | 13 | import java.net.InetSocketAddress; 14 | import java.util.ArrayList; 15 | import java.util.concurrent.LinkedBlockingQueue; 16 | import java.util.concurrent.TimeUnit; 17 | 18 | import io.netty.bootstrap.Bootstrap; 19 | import io.netty.channel.ChannelFuture; 20 | import io.netty.channel.ChannelInitializer; 21 | import io.netty.channel.ChannelOption; 22 | import io.netty.channel.EventLoopGroup; 23 | import io.netty.channel.nio.NioEventLoopGroup; 24 | import io.netty.channel.socket.SocketChannel; 25 | import io.netty.channel.socket.nio.NioSocketChannel; 26 | import io.netty.handler.codec.LengthFieldBasedFrameDecoder; 27 | import io.netty.handler.codec.LengthFieldPrepender; 28 | import io.netty.handler.codec.protobuf.ProtobufDecoder; 29 | import io.netty.handler.codec.protobuf.ProtobufEncoder; 30 | import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; 31 | import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; 32 | import io.netty.handler.codec.string.StringDecoder; 33 | import io.netty.handler.codec.string.StringEncoder; 34 | import io.netty.handler.timeout.IdleStateHandler; 35 | import io.netty.util.CharsetUtil; 36 | import io.reactivex.Observable; 37 | import io.reactivex.functions.Consumer; 38 | import io.reactivex.schedulers.Schedulers; 39 | 40 | /** 41 | * netty长连接 42 | */ 43 | public class NettyConnectionService implements IConnectionService { 44 | private String host; 45 | private int port; 46 | private Bootstrap bootstrap; 47 | public SocketChannel socketChannel; 48 | private NettyClientHandler driverNettyClientHandler; 49 | private static final int RECONNECT_DELAY = 3000; 50 | private ArrayList connectionListeners; 51 | private Gson gson; 52 | private LinkedBlockingQueue messageQueue; 53 | private Thread sendThread; 54 | private IInitializeData iInitializeData; 55 | 56 | @Override 57 | public void create(String host, int port, IInitializeData iInitializeData) { 58 | this.iInitializeData = iInitializeData; 59 | this.host = host; 60 | this.port = port; 61 | connectionListeners = new ArrayList<>(); 62 | createBootstrap(iInitializeData); 63 | gson = new Gson(); 64 | messageQueue = new LinkedBlockingQueue(); 65 | createSendThread(); 66 | } 67 | 68 | @Override 69 | public void addListener(IConnectionListener iConnectionListener) { 70 | connectionListeners.add(iConnectionListener); 71 | } 72 | 73 | @Override 74 | public void removeListener(IConnectionListener iConnectionListener) { 75 | connectionListeners.remove(iConnectionListener); 76 | } 77 | 78 | 79 | @SuppressLint("CheckResult") 80 | @Override 81 | public void connect() { 82 | if (this.socketChannel != null && this.socketChannel.isOpen()) { 83 | return; 84 | } 85 | if (this.socketChannel != null) { 86 | socketChannel.close(); 87 | } 88 | if (bootstrap == null) { 89 | createBootstrap(iInitializeData); 90 | } 91 | if (sendThread != null && !sendThread.isAlive()) { 92 | createSendThread(); 93 | } 94 | try { 95 | Observable.timer(3, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).subscribe(new Consumer() { 96 | @Override 97 | public void accept(Long aLong) throws Exception { 98 | ChannelFuture future = null; 99 | future = bootstrap.connect(new InetSocketAddress(host, port)).sync(); 100 | if (future.isSuccess()) { 101 | socketChannel = (SocketChannel) future.channel(); 102 | } else { 103 | future.channel().closeFuture().sync(); 104 | if (socketChannel != null) { 105 | socketChannel.eventLoop().schedule(() -> { 106 | bootstrap.connect(); 107 | }, RECONNECT_DELAY, TimeUnit.MILLISECONDS); 108 | } 109 | 110 | } 111 | } 112 | }, new Consumer() { 113 | @Override 114 | public void accept(Throwable throwable) throws Exception { 115 | connect(); 116 | } 117 | }); 118 | 119 | } catch (Exception e) { 120 | Observable.timer(3, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).subscribe(new Consumer() { 121 | @Override 122 | public void accept(Long aLong) throws Exception { 123 | connect(); 124 | } 125 | }); 126 | e.printStackTrace(); 127 | } 128 | } 129 | 130 | @Override 131 | public void disConnect() { 132 | if (socketChannel != null) { 133 | socketChannel.close(); 134 | } 135 | if (driverNettyClientHandler != null) { 136 | driverNettyClientHandler.destroy(); 137 | driverNettyClientHandler = null; 138 | } 139 | bootstrap = null; 140 | sendThread.interrupt(); 141 | } 142 | 143 | @Override 144 | public void sendMessage(ISendMessage sendMessage, boolean isNeedReTry) { 145 | if (isNeedReTry) { 146 | try { 147 | messageQueue.put(sendMessage); 148 | } catch (InterruptedException e) { 149 | e.printStackTrace(); 150 | } 151 | } else { 152 | if (socketChannel != null) { 153 | if (iInitializeData.getAgreement() == ConnectionAgreement.STRING) { 154 | if (sendMessage.getData() instanceof String) { 155 | socketChannel.writeAndFlush((String) sendMessage.getData()); 156 | } else { 157 | socketChannel.writeAndFlush(gson.toJson(sendMessage.getData())); 158 | } 159 | } else if (iInitializeData.getAgreement() == ConnectionAgreement.JSON) { 160 | socketChannel.writeAndFlush(gson.toJson(sendMessage.getData())); 161 | } else if (iInitializeData.getAgreement() == ConnectionAgreement.PROTOBUF) { 162 | socketChannel.writeAndFlush(sendMessage.getData()); 163 | } 164 | } 165 | } 166 | if (connectionListeners != null) { 167 | for (IConnectionListener iConnectionListener : connectionListeners) { 168 | iConnectionListener.sendMessage(sendMessage); 169 | } 170 | } 171 | } 172 | 173 | @Override 174 | public boolean isConnect() { 175 | if (socketChannel != null) { 176 | return socketChannel.isOpen(); 177 | } 178 | return false; 179 | } 180 | 181 | private void createBootstrap(IInitializeData iInitializeData) { 182 | EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); 183 | bootstrap = new Bootstrap(); 184 | bootstrap.channel(NioSocketChannel.class); 185 | bootstrap.option(ChannelOption.SO_KEEPALIVE, true); 186 | bootstrap.group(eventLoopGroup); 187 | bootstrap.remoteAddress(host, port); 188 | bootstrap.handler(new ChannelInitializer() { 189 | @Override 190 | protected void initChannel(SocketChannel socketChannel) { 191 | socketChannel.pipeline().addLast(new IdleStateHandler(3, 3, 0)); 192 | socketChannel.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); 193 | socketChannel.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4)); 194 | if (iInitializeData.getAgreement() == ConnectionAgreement.PROTOBUF) { 195 | socketChannel.pipeline().addLast(new ProtobufVarint32FrameDecoder()) 196 | .addLast(new ProtobufDecoder((MessageLite) iInitializeData.agreementMessageData())) 197 | .addLast(new ProtobufVarint32LengthFieldPrepender()) 198 | .addLast(new ProtobufEncoder()); 199 | } else { 200 | socketChannel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8)); 201 | socketChannel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); 202 | } 203 | driverNettyClientHandler = new NettyClientHandler(false, iInitializeData, connectionListeners, NettyConnectionService.this); 204 | socketChannel.pipeline().addLast(driverNettyClientHandler); 205 | } 206 | }); 207 | } 208 | 209 | 210 | /** 211 | * 创建发送消息的线程池 212 | */ 213 | private void createSendThread() { 214 | if (sendThread != null) { 215 | sendThread.interrupt(); 216 | } 217 | sendThread = new Thread(new Runnable() { 218 | @Override 219 | public void run() { 220 | ISendMessage message = null; 221 | while (true) { 222 | message = messageQueue.poll(); 223 | boolean isSendSuccess = false; 224 | try { 225 | while (!isSendSuccess && message != null) { 226 | if (socketChannel != null) { 227 | if (iInitializeData.getAgreement() == ConnectionAgreement.STRING) { 228 | if (message.getData() instanceof String) { 229 | isSendSuccess = socketChannel.writeAndFlush((String) message.getData()).await(3000); 230 | } else { 231 | isSendSuccess = socketChannel.writeAndFlush(gson.toJson(message.getData())).await(3000); 232 | } 233 | } else if (iInitializeData.getAgreement() == ConnectionAgreement.JSON) { 234 | isSendSuccess = socketChannel.writeAndFlush(gson.toJson(message.getData())).await(3000); 235 | } else if (iInitializeData.getAgreement() == ConnectionAgreement.PROTOBUF) { 236 | isSendSuccess = socketChannel.writeAndFlush(message.getData()).await(3000); 237 | } 238 | } 239 | } 240 | } catch (InterruptedException e) { 241 | e.printStackTrace(); 242 | } 243 | } 244 | } 245 | }); 246 | sendThread.start(); 247 | } 248 | } 249 | -------------------------------------------------------------------------------- /connection/src/main/java/com/yun/connection/impl/NettyClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.yun.connection.impl; 2 | 3 | 4 | import android.util.Log; 5 | 6 | import com.google.gson.Gson; 7 | import com.yun.connection.IConnectionService; 8 | import com.yun.connection.listener.IConnectionListener; 9 | import com.yun.connection.model.ConnectionAgreement; 10 | import com.yun.connection.model.IInitializeData; 11 | 12 | import java.util.ArrayList; 13 | import java.util.LinkedList; 14 | import java.util.concurrent.TimeUnit; 15 | 16 | import io.netty.channel.ChannelHandlerContext; 17 | import io.netty.channel.SimpleChannelInboundHandler; 18 | import io.netty.channel.socket.SocketChannel; 19 | import io.netty.handler.timeout.IdleStateEvent; 20 | import io.netty.util.ReferenceCountUtil; 21 | import io.reactivex.Observable; 22 | import io.reactivex.functions.Consumer; 23 | import io.reactivex.schedulers.Schedulers; 24 | 25 | /** 26 | * NettyClientHandler 27 | * 28 | * @author enyva 29 | * @version 2017/03/20 30 | */ 31 | public class NettyClientHandler extends SimpleChannelInboundHandler { 32 | 33 | protected static final String TAG = NettyClientHandler.class.getSimpleName(); 34 | private static final Object lock = new Object(); 35 | private static Gson gson = new Gson(); 36 | //是否不断线重连,主动关闭 37 | private boolean is_force_close = false; 38 | // Sleep 3 seconds before a reconnection attempt. 39 | private static final int RECONNECT_DELAY_HANDLER = 5; 40 | // how many times of not receiving pong message. 41 | private static final int TIMES_UNRECEIVED_PONG = 10; 42 | 43 | private static final int SIZE_LINKED_QUEUE = 4; 44 | 45 | 46 | private volatile int mUnReceivedPongTimes = 0; 47 | 48 | public static LinkedList sChannelActiveQueue = new LinkedList<>(); 49 | public static LinkedList sChannelInActiveQueue = new LinkedList<>(); 50 | private ArrayList connectionListeners; 51 | private boolean isConnect = false; 52 | private IConnectionService iConnectionService; 53 | private IInitializeData iInitializeData; 54 | 55 | public NettyClientHandler(boolean is_force_close, IInitializeData iInitializeData, ArrayList connectionListeners 56 | , IConnectionService iConnectionService) { 57 | this.is_force_close = is_force_close; 58 | this.connectionListeners = connectionListeners; 59 | this.iConnectionService = iConnectionService; 60 | this.iInitializeData = iInitializeData; 61 | } 62 | 63 | public void setIs_force_close(boolean b) { 64 | this.is_force_close = b; 65 | } 66 | 67 | //利用写空闲发送心跳检测消息 68 | @Override 69 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { 70 | try { 71 | if (evt instanceof IdleStateEvent) { 72 | IdleStateEvent e = (IdleStateEvent) evt; 73 | Log.i("NettyClientHandler", "NettyClientHandler status : " + e.state().name()); 74 | switch (e.state()) { 75 | case WRITER_IDLE: 76 | Log.d("", "WRITER_IDLE - mUnReceivedPongTimes: " + mUnReceivedPongTimes); 77 | break; 78 | case READER_IDLE: 79 | mUnReceivedPongTimes++; 80 | if (mUnReceivedPongTimes > TIMES_UNRECEIVED_PONG) { 81 | mUnReceivedPongTimes = 0; 82 | Log.d(TAG, "mUnReceivedPongTimes >= TIMES_UNRECEIVED_PONG ,mUnReceivedPongTimes = " 83 | + mUnReceivedPongTimes); 84 | ctx.close(); 85 | } else { 86 | if (iInitializeData.getHeartBeatMessage() != null && iInitializeData.getHeartBeatMessage().getData() != null) { 87 | if (iInitializeData.getAgreement() == ConnectionAgreement.STRING) { 88 | if (iInitializeData.getHeartBeatMessage().getData() instanceof String) { 89 | ctx.writeAndFlush(((String) iInitializeData.getHeartBeatMessage().getData())); 90 | } else { 91 | ctx.writeAndFlush(gson.toJson(iInitializeData.getHeartBeatMessage().getData())); 92 | } 93 | } else if (iInitializeData.getAgreement() == ConnectionAgreement.JSON) { 94 | ctx.writeAndFlush(gson.toJson(iInitializeData.getHeartBeatMessage().getData())); 95 | } else if (iInitializeData.getAgreement() == ConnectionAgreement.PROTOBUF) { 96 | ctx.writeAndFlush(iInitializeData.getHeartBeatMessage().getData()); 97 | } 98 | if (connectionListeners != null) { 99 | for (IConnectionListener iConnectionListener : connectionListeners) { 100 | iConnectionListener.sendMessage(iInitializeData.getHeartBeatMessage()); 101 | } 102 | } 103 | } 104 | } 105 | break; 106 | default: 107 | break; 108 | } 109 | } 110 | } catch (Exception e) { 111 | e.printStackTrace(); 112 | } 113 | } 114 | 115 | @Override 116 | public void channelActive(ChannelHandlerContext ctx) { 117 | try { 118 | SocketChannel activeSocketChannel = (SocketChannel) ctx.channel(); 119 | 120 | Observable.timer(0, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).subscribe(new Consumer() { 121 | @Override 122 | public void accept(Long aLong) throws Exception { 123 | if (iInitializeData.getChannelActiveMessage() != null && iInitializeData.getChannelActiveMessage().getData() != null) { 124 | boolean isSendSuccess = false; 125 | while (!isSendSuccess) { 126 | if (iInitializeData.getAgreement() == ConnectionAgreement.STRING) { 127 | if (iInitializeData.getChannelActiveMessage().getData() instanceof String) { 128 | isSendSuccess = ctx.writeAndFlush((String) iInitializeData.getChannelActiveMessage().getData()).await(3000); 129 | } else { 130 | isSendSuccess = ctx.writeAndFlush(gson.toJson(iInitializeData.getChannelActiveMessage().getData())).await(3000); 131 | } 132 | } else if (iInitializeData.getAgreement() == ConnectionAgreement.JSON) { 133 | isSendSuccess = activeSocketChannel.writeAndFlush(gson.toJson(iInitializeData.getChannelActiveMessage().getData())).await(3000); 134 | } else if (iInitializeData.getAgreement() == ConnectionAgreement.PROTOBUF) { 135 | isSendSuccess = activeSocketChannel.writeAndFlush(iInitializeData.getChannelActiveMessage().getData()).await(3000); 136 | } 137 | if (connectionListeners != null) { 138 | for (IConnectionListener iConnectionListener : connectionListeners) { 139 | iConnectionListener.sendMessage(iInitializeData.getChannelActiveMessage()); 140 | } 141 | } 142 | } 143 | 144 | } 145 | } 146 | }); 147 | 148 | synchronized (lock) { 149 | long currentTimeStamp = System.currentTimeMillis(); 150 | sChannelActiveQueue.add(activeSocketChannel.id().toString() + ":" + activeSocketChannel.isOpen() + ":" + currentTimeStamp); 151 | 152 | for (String channelInfo : sChannelActiveQueue) { 153 | Log.d(TAG, "TCP Log - [mChannelActiveQueue] channelInfo = " + channelInfo); 154 | } 155 | Log.d(TAG, "TCP Log-------------------------- size = " + sChannelActiveQueue.size()); 156 | if (sChannelActiveQueue.size() > SIZE_LINKED_QUEUE) { 157 | Log.d(TAG, "TCP Log remove first channelInfo = " + sChannelActiveQueue.pollFirst()); 158 | } 159 | } 160 | ctx.fireChannelActive(); 161 | } catch (Exception e) { 162 | e.printStackTrace(); 163 | } 164 | } 165 | 166 | //这里是断线要进行的操作 167 | @Override 168 | public void channelInactive(ChannelHandlerContext ctx) { 169 | if (is_force_close) { 170 | return; 171 | } 172 | try { 173 | super.channelInactive(ctx); 174 | if (connectionListeners != null) { 175 | for (IConnectionListener iConnectionListener : connectionListeners) { 176 | isConnect = false; 177 | iConnectionListener.onDisConnect(); 178 | } 179 | } 180 | SocketChannel inActiveSocketChannel = (SocketChannel) ctx.channel(); 181 | Log.i(TAG, "TCP Log: channelInactive 服务端连接中断, local port:" + inActiveSocketChannel.localAddress().getAddress() 182 | + ":" + inActiveSocketChannel.localAddress().getPort() + " channelId:" + inActiveSocketChannel.id()); 183 | mUnReceivedPongTimes = 0; 184 | synchronized (lock) { 185 | long currentTimeStamp = System.currentTimeMillis(); 186 | String lastChannelInfo = sChannelActiveQueue.peekLast(); 187 | Log.i(TAG, "TCP Log -- active peekLast = " + lastChannelInfo + " , 正常的斷線重連得和channelAactive 的id不同"); 188 | Log.d(TAG, "TCP Log - 重要, 目前active latest channelId = " + lastChannelInfo.substring(0, lastChannelInfo.indexOf(":"))); 189 | String latestChannelId = lastChannelInfo.substring(0, lastChannelInfo.indexOf(":")); 190 | sChannelInActiveQueue.add(inActiveSocketChannel.id().toString() + ":" + inActiveSocketChannel.isOpen() + ":" + currentTimeStamp); 191 | for (String channelInfo : sChannelInActiveQueue) { 192 | Log.i(TAG, "TCP Log [sChannelInActiveQueue] channelInfo = " + channelInfo); 193 | } 194 | Log.d(TAG, "TCP Log-------------------------- size = " + sChannelInActiveQueue.size()); 195 | if (sChannelInActiveQueue.size() > SIZE_LINKED_QUEUE) { 196 | Log.d(TAG, "TCP Log remove first channelInfo = " + sChannelInActiveQueue.pollFirst()); 197 | } 198 | if (latestChannelId.equals(inActiveSocketChannel.id().toString())) { 199 | Log.i(TAG, "TCP Log , channelId 與last channelActive 相同, reconnect"); 200 | ctx.channel().eventLoop().schedule(() -> { 201 | iConnectionService.connect(); 202 | }, RECONNECT_DELAY_HANDLER, TimeUnit.SECONDS); 203 | } else { 204 | // 如果最新的 channelActive 的channel Id 和 channelInactive callback 回來的channel Id 不同, 205 | // 表示有多餘的重複連線了, do not reconnect 206 | Log.i(TAG, "TCP Log , =\\=channelId 與last channelActive 不同, normal - disconnected"); 207 | } 208 | } 209 | } catch (Exception e) { 210 | e.printStackTrace(); 211 | } 212 | } 213 | 214 | //这里是出现异常的话要进行的操作 215 | @Override 216 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 217 | try { 218 | ctx.close(); 219 | Log.d("TCP Log", "出现异常了。。。。。。。。。。。。。" + cause.toString()); 220 | } catch (Exception e) { 221 | e.printStackTrace(); 222 | } 223 | } 224 | 225 | 226 | /** 227 | * 销毁 228 | */ 229 | public void destroy() { 230 | iConnectionService = null; 231 | } 232 | 233 | 234 | @Override 235 | protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception { 236 | try { 237 | Object returnMsg = null; 238 | mUnReceivedPongTimes = 0; 239 | if (connectionListeners != null) { 240 | for (IConnectionListener iConnectionListener : connectionListeners) { 241 | if (!isConnect) { 242 | isConnect = true; 243 | iConnectionListener.onConnect(); 244 | } 245 | if (iInitializeData.getAgreement() == ConnectionAgreement.STRING) { 246 | returnMsg = iConnectionListener.onReceive(msg.toString()); 247 | } else if (iInitializeData.getAgreement() == ConnectionAgreement.JSON) { 248 | returnMsg = iConnectionListener.onReceive(gson.fromJson(msg.toString(), iConnectionListener.getMessageType())); 249 | } else if (iInitializeData.getAgreement() == ConnectionAgreement.PROTOBUF) { 250 | returnMsg = iConnectionListener.onReceive(msg); 251 | } 252 | if (returnMsg != null) { 253 | break; 254 | } 255 | } 256 | } 257 | if (returnMsg != null) { 258 | if (iInitializeData.getAgreement() == ConnectionAgreement.STRING) { 259 | if (returnMsg instanceof String) { 260 | ReferenceCountUtil.release(((String) returnMsg)); 261 | } else { 262 | ReferenceCountUtil.release(gson.toJson(returnMsg)); 263 | } 264 | } else if (iInitializeData.getAgreement() == ConnectionAgreement.JSON) { 265 | ReferenceCountUtil.release(gson.toJson(returnMsg)); 266 | } else if (iInitializeData.getAgreement() == ConnectionAgreement.PROTOBUF) { 267 | ReferenceCountUtil.release(returnMsg); 268 | } 269 | } 270 | } catch (Exception e) { 271 | e.printStackTrace(); 272 | } 273 | } 274 | } 275 | --------------------------------------------------------------------------------