Skip to content

Instantly share code, notes, and snippets.

@usmansaleem
Created December 4, 2017 06:17
Show Gist options
  • Save usmansaleem/918d9a19ca7a940c90b9541008f5b726 to your computer and use it in GitHub Desktop.
Save usmansaleem/918d9a19ca7a940c90b9541008f5b726 to your computer and use it in GitHub Desktop.
A very simple vertx based websocket example connecting to Vertx SockJS.
package info.usmans.blog.vertx.examples
import io.vertx.core.AbstractVerticle
import io.vertx.core.Vertx
import io.vertx.core.http.HttpClient
import io.vertx.core.http.WebSocketFrame
import io.vertx.core.json.JsonObject
fun main(args: Array<String>) {
Vertx.vertx().deployVerticle(WebSocketClientExample())
println("Running WebSockerClientExample!")
}
/**
* A Vertx Verticle to connect to our custom websocket
*/
class WebSocketClientExample : AbstractVerticle() {
override fun start() {
val client = vertx.createHttpClient()
openWebSocketConnection(client)
}
private fun openWebSocketConnection(client: HttpClient) {
client.websocket(8080, "localhost", "/eventbus/websocket", { ws ->
var timerId: Long = 0
println("Connected!")
//simulate vertx eventbus on SockJS endpoint
val reg = JsonObject().put("type", "register").put("address", "news-feed")
ws.writeFrame(WebSocketFrame.textFrame(reg.encode(), true))
ws.handler({ buff ->
//do the actual task here ...
println(buff)
})
ws.closeHandler({
println("Cancelling ping timer ...")
vertx.cancelTimer(timerId)
})
//ping to keep the connection open ...
timerId = vertx.setPeriodic(5000) { t ->
ws.writeTextMessage("{\"type\":\"ping\"}")
}
}, { failureHandler ->
println("ERROR: Unable to connect to websocket: " + failureHandler.message)
vertx.setTimer(1000, {
openWebSocketConnection(client) //recursive baby ...
})
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment