首页 > 解决方案 > Ktor reflection to create custom WebSocket session doesn't update constructor parameters

问题描述

I'm working on a web app written with a Kotlin backend and React frontend, that uses Ktor to set up a web server. I'm currently trying to add functionality that requires a WebSocket connection, and to maintain state across the WebSocket session, using the custom session model from the Ktor example chat app here: https://github.com/ktorio/ktor-samples/tree/master/app/chat/src.

However, I'm getting an issue with the reflection Ktor is doing to create these sessions.

The custom session is defined as follows:

data class THavalonUserSession(val id: String,
 var name: String, var socket: DefaultWebSocketSession?)

And is initialized in the following block:

      intercept(ApplicationCallPipeline.Features) {
          if (call.sessions.get<THavalonUserSession>() == null) {
              call.sessions.set(THavalonUserSession(generateNonce(), "", null))
            }
        }

When I run the application on Chrome, either with built React or in React development mode, I get the following server side error:

java.lang.IllegalArgumentException: Couldn't instantiate type class main.THavalonUserSession for parameters [id, name]

When I run it on Firefox, it works, until I change the socket parameter name from socket to mySocket, at which point it gives the error:

java.lang.IllegalArgumentException: Couldn't instantiate type class main.THavalonUserSession for parameters [id, name, socket]

The only thing I can think of is that it's somehow caching class names in the browser, but that makes no sense to me.

标签: kotlinwebsocketktor

解决方案


Turns out Ktor stores reflection data in local storage. Why? I have no idea. Clear browser data to solve this issue.


推荐阅读