日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

稳定的手机端服务器,[Ktor] 实现移动端的 Ktor 服务器

發(fā)布時(shí)間:2025/4/16 编程问答 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 稳定的手机端服务器,[Ktor] 实现移动端的 Ktor 服务器 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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

好了,廢話不多說,我們來實(shí)現(xiàn)一個(gè)在手機(jī)上的服務(wù)器。

首先還是 建立項(xiàng)目 吧,先改 gradle 腳本,由于需要用到 Ktor,就需要先把相關(guān)的 maven 庫加入到項(xiàng)目的腳本內(nèi):

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 腳本,加入對(duì) 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

}

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

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

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 的架子也有了,這份代碼目前還不能編譯,因?yàn)槿绷?Application::module。下面就來補(bǔ)足它。

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

fun Application.module() {

routing {

basicRoute()

}

}

fun Routing.basicRoute() {

get("/") {

call.respondBytes { WOK_HTML }

}

}

這些代碼就足夠了,你只需要再補(bǔ)一點(diǎn)點(diǎn)代碼,比如說 startService,就可以順利的在手機(jī)上運(yùn)行起服務(wù)器程序了。

此時(shí)我們可以嘗試在手機(jī)上用瀏覽器訪問 http://0.0.0.0:8080,看看是否有內(nèi)容返回,當(dāng)看到有頁面內(nèi)容時(shí),即證明服務(wù)運(yùn)行正常。

當(dāng)然此時(shí)我們是完全不能用 app 自身去訪問的,由于 Android 高版本對(duì) https 的要求,我們還需要加入配置文件來使 app 自身可以請(qǐng)求 http 服務(wù):

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

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

首先你需要有一定的知識(shí)儲(chǔ)備,請(qǐng)先參考這篇(點(diǎn)擊進(jìn)入),然后把相應(yīng)的代碼拷去 Android 項(xiàng)目里:

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 包轉(zhuǎn)換為 Android 可以識(shí)別的格式:

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

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

PluginClass=com.rarnu.sample.plugin.PluginRoutingKt

RoutingMethods= pluginRouting

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

現(xiàn)在讓我們?cè)賳?dòng)一下程序,看看是否插件的內(nèi)容已經(jīng)可以成功被訪問到。

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

不過這沒有關(guān)系,因?yàn)槲以镜拇蛩憔褪亲屓罩据敵龅?TextView 內(nèi),所以這里需要的是一個(gè)對(duì) print 方法的重定向,具體實(shí)現(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)

}

}

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

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

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

最后說一下幾個(gè)必須注意的坑:

engine.start(false),此處必須為 false,寫 Ktor 的時(shí)候這里會(huì)寫 true,因?yàn)槲覀冃枰M(jìn)程等待,但是在 Android 端是不可以等待的,否則會(huì)造成阻塞引起 ANR。

engine.stop(),必須放在線程里執(zhí)行,放在主線程同樣會(huì)引起阻塞。

embeddedServer 引擎選哪個(gè),目前實(shí)測結(jié)果是,Netty 更穩(wěn)定,而 Tomcat 時(shí)有 ANR,其他引擎暫時(shí)未試,不過按官方的說法,還是 Netty 更推薦一些。

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

總結(jié)

以上是生活随笔為你收集整理的稳定的手机端服务器,[Ktor] 实现移动端的 Ktor 服务器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。