[Ktor] 實現(xiàn)移動端的 Ktor 服務器

不知現(xiàn)在有多少人會拿自己的手機來編寫程序,又或是拿來當成服務器使用,但是在手機上跑起服務程序的確是一個非常吸引人的玩法,當然了,不僅僅是玩,還是有很多實用場景的,比如說像《多看》的從電腦向手機傳書,利用的就是在手機端啟動一個服務器,然后通過局域網(wǎng)內訪問的原理實現(xiàn)的。

好了,廢話不多說,我們來實現(xiàn)一個在手機上的服務器。


首先還是 建立項目 吧,先改 gradle 腳本,由于需要用到 Ktor,就需要先把相關的 maven 庫加入到項目的腳本內:

buildscript {
    ext.kotlin_version = '1.3.61'
    ext.ktor_version = '1.2.1'
    ... ...
}
... ...
allprojects {
    repositories {
        ... ...
        maven { url "http://dl.bintray.com/kotlin/ktor" }
        maven { url "https://dl.bintray.com/kotlin/kotlinx" }
    }
}

然后再改一下 app 下的 gradle 腳本,加入對 Ktor 的依賴:

dependencies {
    ... ...
    implementation "io.ktor:ktor:$ktor_version"
    implementation "io.ktor:ktor-server-netty:$ktor_version"
    implementation "io.ktor:ktor-websockets:$ktor_version"
    implementation "io.ktor:ktor-server-core:$ktor_version"
    implementation "io.ktor:ktor-server-host-common:$ktor_version"
    implementation "io.ktor:ktor-server-sessions:$ktor_version"
    implementation "io.ktor:ktor-client-okhttp:$ktor_version"
    implementation "mysql:mysql-connector-java:8.0.15"
}

androidExtensions {
    experimental = true
}

這樣我們就擁有了一個最基本的架子,雖然還沒有開始寫任何代碼,至少環(huán)境已經(jīng)備齊了。


接著來 實現(xiàn) KtorService,其實很簡單的,只需要把原本屬于 Ktor 的啟動服務代碼搬來就行:

class KtorService: Service() {

    companion object {
        private const val N_CHANNEL = "KtorServiceChannel"
        private const val N_NOTIFY_ID = 10010001
    }

    private var engine: ApplicationEngine? = null

    override fun onBind(intent: Intent?) = null

    override fun onCreate() {
        super.onCreate()
        goForeground()
        println("Server starting...")

        if (engine == null) {
            engine = embeddedServer(Netty, 8080, module = Application::module)
            engine?.start(false)
        }
    }

    override fun onDestroy() {
        println("Server stopping...")
        if (engine != null) {
            thread {
                engine?.stop(1, 1, TimeUnit.SECONDS)
                engine = null
                println("Server Stopped.")
            }
        }
        stopForeground(true)
        super.onDestroy()
    }

    private fun goForeground() {
        if (Build.VERSION.SDK_INT >= 26) {
            val channel = NotificationChannel(N_CHANNEL, N_CHANNEL, NotificationManager.IMPORTANCE_NONE)
            (getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager)?.createNotificationChannel(channel)
            val notification = Notification.Builder(this, N_CHANNEL)
                    .setContentTitle(resStr(R.string.app_name))
                    .setSmallIcon(R.drawable.ic_notify)
                    .build()
            startForeground(N_NOTIFY_ID, notification)
        }
    }
}

好了,就是如此簡單,Service 的架子也有了,這份代碼目前還不能編譯,因為缺了 Application::module。下面就來補足它。


下面來補足 Application::module,如果你對 Ktor 很熟悉的話,可以直接寫出如下代碼:

fun Application.module() {
    routing {
        basicRoute()
    }
}

fun Routing.basicRoute() {
    get("/") {
        call.respondBytes { WOK_HTML }
    }
}

這些代碼就足夠了,你只需要再補一點點代碼,比如說 startService,就可以順利的在手機上運行起服務器程序了。


此時我們可以嘗試在手機上用瀏覽器訪問 http://0.0.0.0:8080,看看是否有內容返回,當看到有頁面內容時,即證明服務運行正常。

當然此時我們是完全不能用 app 自身去訪問的,由于 Android 高版本對 https 的要求,我們還需要加入配置文件來使 app 自身可以請求 http 服務:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

可能你會問了,這樣寫一個靜態(tài)的服務器一點意義都沒有,如果要做得靈活一點,可以在程序外實現(xiàn)邏輯,然后讓 Ktor 來提供服務嗎?

這么做當然是可以的,這篇主要想說的也是這個,我更希望實現(xiàn)一個容器,然后讓用戶自己來填充邏輯。那現(xiàn)在就來看看如何在 Android 端的 Ktor 服務上動態(tài)加載吧。

首先你需要有一定的知識儲備,請先參考這篇(點擊進入),然后把相應的代碼拷去 Android 項目里:

lateinit var appContext: Context

fun Application.module() {
    routing {
        basicRoute()
        loadLibraries()
    }
}

fun Routing.basicRoute() {
    get("/") {
        call.respondBytes { WOK_HTML }
    }
}

fun Routing.loadLibraries() =
        File(Environment.getExternalStorageDirectory(), "KTOR").apply { if (!exists()) mkdirs() }
                .listFiles { _, name -> name.endsWith(".cfg") }.forEach { file ->
                    val m = file.readLines().filter { it.trim() != "" }.map { it.split("=").run { Pair(this[0], this[1]) } }.toMap()
                    loadLibrary(file, m["PluginClass"] ?: "", m["RoutingMethods"] ?: "")
                }

private fun Routing.loadLibrary(file: File, cls: String, method: String) {
    val fJar = File(file.absolutePath.substringBeforeLast(".") + ".jar")
    val fOut = File(Environment.getExternalStorageDirectory(), "KTOR").absolutePath
    if (fJar.exists() && cls != "" && method != "") {
        try {
            DexClassLoader(fJar.absolutePath, fOut, null, appContext.classLoader)
                    .loadClass(cls)
                    .getDeclaredMethod(method, Routing::class.java)
                    .invoke(null, this)
            println("load library: ${fJar.name}")
        } catch (th: Throwable) {
            println("load library ${fJar.name} failed, reason: $th")
        }
    }
}

需要注意的是,在 Android 上使用 URLClassLoader 是沒有意義的,必須使用 DexClassLoader,并且也需要將通常的 jar 包轉換為 Android 可以識別的格式:

$ dx --dex --output=Sample-dex.jar Sample-1.0.0.jar

依據(jù)上面的代碼,其實我已經(jīng)約定了插件的加載方式,需要加入額外的配置文件如下:

PluginClass=com.rarnu.sample.plugin.PluginRoutingKt
RoutingMethods= pluginRouting

將此內容保存為 Sample-dex.cfg 并連同 jar 文件一起 push 到 /sdcard/KTOR/ 內,就大功告成了。

現(xiàn)在讓我們再啟動一下程序,看看是否插件的內容已經(jīng)可以成功被訪問到。


可能你已經(jīng)注意到了,在上述代碼中,我用的打日志函數(shù)是 println,而并非 Android 內常用的 Log.x,這會導致日志無法被看到。

不過這沒有關系,因為我原本的打算就是讓日志輸出到 TextView 內,所以這里需要的是一個對 print 方法的重定向,具體實現(xiàn)還是看代碼吧:

class RedirectStream(val callback: (String) -> Unit): OutputStream() {
    override fun write(b: Int) {
        // do nothing
    }
    override fun write(b: ByteArray, off: Int, len: Int) {
        val s = String(b.dropLast(b.size - len).toByteArray()).trim()
        if (s != "") callback(s)
    }
}

自定義一個重定向流,用來把接受到的東西 callback 出去,然后就可以有一個騷操作了:

System.setOut(PrintStream(RedirectStream { runOnMainThread { tvOutput.append("$it\n") } }))

好了,這樣就完成了對 print 的重定向,當你在代碼中執(zhí)行 print 系列方法時,就可以把這些內容直接輸出到 TextView 里了,這會使得對于插件的開發(fā),調試都變得更加方便。


最后說一下幾個必須注意的坑:

  1. engine.start(false),此處必須為 false,寫 Ktor 的時候這里會寫 true,因為我們需要進程等待,但是在 Android 端是不可以等待的,否則會造成阻塞引起 ANR。
  2. engine.stop(),必須放在線程里執(zhí)行,放在主線程同樣會引起阻塞。
  3. embeddedServer 引擎選哪個,目前實測結果是,Netty 更穩(wěn)定,而 Tomcat 時有 ANR,其他引擎暫時未試,不過按官方的說法,還是 Netty 更推薦一些。

好了,東西做出來了,直接開源(點此去撈代碼)大家一起玩,后續(xù)我也會在 KtGen 內提供開發(fā)插件的模板,敬請期待啦。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容