Created
November 24, 2017 15:28
-
-
Save tgirard12/eb9c38ffb5d2a997055d891e80341a9c to your computer and use it in GitHub Desktop.
Spring Reactive WebSocket Extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.boot.SpringApplication | |
import org.springframework.boot.autoconfigure.SpringBootApplication | |
import org.springframework.context.ApplicationContextInitializer | |
import org.springframework.context.support.GenericApplicationContext | |
import org.springframework.web.reactive.config.EnableWebFlux | |
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping | |
import org.springframework.web.reactive.socket.WebSocketHandler | |
import org.springframework.web.reactive.socket.WebSocketSession | |
import org.springframework.context.support.beans | |
import reactor.core.publisher.Mono | |
import java.util.HashMap | |
@SpringBootApplication | |
@EnableWebFlux | |
class App | |
fun main(args: Array<String>) { | |
SpringApplication(App::class.java).apply { | |
addInitializers(ApplicationContextInitializer<GenericApplicationContext> { | |
beans { | |
bean { | |
wsRouter { | |
WS("/webSocket") { session -> | |
session.send( | |
session.receive().map { session.textMessage(it.payloadAsText) } | |
) | |
} | |
} | |
} | |
bean { webSocketHandlerAdapter() } | |
} | |
}) | |
}.run(*args) | |
} | |
fun wsRouter(f: WsRoutes.() -> Unit): SimpleUrlHandlerMapping = | |
SimpleUrlHandlerMapping().apply { | |
WsRoutes().let { | |
f(it) | |
urlMap = it.urls | |
order = it.order | |
} | |
} | |
@Suppress("FunctionName") | |
fun WsRoutes.WS(url: String, f: (session: WebSocketSession) -> Mono<Void>) { | |
urls.put(url, WebSocketHandler { session -> f(session) }) | |
} | |
class WsRoutes( | |
val urls: HashMap<String, WebSocketHandler> = hashMapOf(), | |
var order: Int = Int.MAX_VALUE | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment