I am trying to run trivial chat sample on an Android device with ktor websocket but it does not work well. I have an error when installing websocket server in MainActivity
Here is build.gradle for ktor websocket
//this is for project
ext.ktor_version = '1.2.5'
maven { url "https://dl.bintray.com/kotlin/ktor" }
//this is for app
packagingOptions {
exclude 'META-INF/*'
}
implementation "io.ktor:ktor-websockets:$ktor_version"
And Here is code for MainActivity
import io.ktor.application.*
import io.ktor.features.*
import io.ktor.http.cio.websocket.*
import io.ktor.http.cio.websocket.CloseReason
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.content.*
import io.ktor.routing.*
import io.ktor.sessions.*
import io.ktor.util.*
import io.ktor.websocket.*
import kotlinx.coroutines.channels.*
import java.time.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
install(WebSockets) {
pingPeriod = Duration.ofSeconds(60) // Disabled (null) by default
timeout = Duration.ofSeconds(15)
maxFrameSize = Long.MAX_VALUE // Disabled (max value). The connection will be closed if surpassed this length.
masking = false
}
}
}
When I build this code on Android Studio, the error is occurred
public fun <P : Pipeline<*, ApplicationCall>, B : Any, F : Any> ???.install(feature: ApplicationFeature<???, WebSockets.WebSocketOptions, WebSockets>, configure: WebSockets.WebSocketOptions.() -> Unit = ...): WebSockets defined in io.ktor.application
Websockets is one of the server features that you can plug into an application, so the context for the install call should be a Ktor application, not an Android Activity. I recommend you to look at Hello world example. Here is your sample code modified:
import io.ktor.application.*
import io.ktor.http.cio.websocket.*
import io.ktor.server.engine.*
import io.ktor.websocket.*
import java.time.Duration
import io.ktor.routing.*
import io.ktor.server.netty.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
embeddedServer(Netty, 4444) {
install(WebSockets) {
pingPeriod = Duration.ofSeconds(60) // Disabled (null) by default
timeout = Duration.ofSeconds(15)
maxFrameSize = Long.MAX_VALUE // Disabled (max value). The connection will be closed if surpassed this length.
masking = false
}
routing {
webSocket("/") {
// ...
}
}
}.start()
}
}
You need to add the following dependencies to make this sample work:
implementation "io.ktor:ktor-server-core:$ktor_version"
implementation "io.ktor:ktor-server-netty:$ktor_version"
implementation "ch.qos.logback:logback-classic:1.2.3" // for logging
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With