[Ktor] 实现移动端的 Ktor 服务器

不知现在有多少人会拿自己的手机来编写程序,又或是拿来当成服务器使用,但是在手机上跑起服务程序的确是一个非常吸引人的玩法,当然了,不仅仅是玩,还是有很多实用场景的,比如说像《多看》的从电脑向手机传书,利用的就是在手机端启动一个服务器,然后通过局域网内访问的原理实现的。

好了,废话不多说,我们来实现一个在手机上的服务器。


首先还是 建立项目 吧,先改 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
}

这样我们就拥有了一个最基本的架子,虽然还没有开始写任何代码,至少环境已经备齐了。


接着来 实现 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 服务:



    
        
            
        
    


可能你会问了,这样写一个静态的服务器一点意义都没有,如果要做得灵活一点,可以在程序外实现逻辑,然后让 Ktor 来提供服务吗?

这么做当然是可以的,这篇主要想说的也是这个,我更希望实现一个容器,然后让用户自己来填充逻辑。那现在就来看看如何在 Android 端的 Ktor 服务上动态加载吧。

首先你需要有一定的知识储备,请先参考这篇(点击进入),然后把相应的代码拷去 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

依据上面的代码,其实我已经约定了插件的加载方式,需要加入额外的配置文件如下:

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

将此内容保存为 Sample-dex.cfg 并连同 jar 文件一起 push 到 /sdcard/KTOR/ 内,就大功告成了。

现在让我们再启动一下程序,看看是否插件的内容已经可以成功被访问到。


可能你已经注意到了,在上述代码中,我用的打日志函数是 println,而并非 Android 内常用的 Log.x,这会导致日志无法被看到。

不过这没有关系,因为我原本的打算就是让日志输出到 TextView 内,所以这里需要的是一个对 print 方法的重定向,具体实现还是看代码吧:

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 的重定向,当你在代码中执行 print 系列方法时,就可以把这些内容直接输出到 TextView 里了,这会使得对于插件的开发,调试都变得更加方便。


最后说一下几个必须注意的坑:

  1. engine.start(false),此处必须为 false,写 Ktor 的时候这里会写 true,因为我们需要进程等待,但是在 Android 端是不可以等待的,否则会造成阻塞引起 ANR。
  2. engine.stop(),必须放在线程里执行,放在主线程同样会引起阻塞。
  3. embeddedServer 引擎选哪个,目前实测结果是,Netty 更稳定,而 Tomcat 时有 ANR,其他引擎暂时未试,不过按官方的说法,还是 Netty 更推荐一些。

好了,东西做出来了,直接开源(点此去捞代码)大家一起玩,后续我也会在 KtGen 内提供开发插件的模板,敬请期待啦。

你可能感兴趣的:([Ktor] 实现移动端的 Ktor 服务器)