Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.its
- import org.eclipse.jetty.websocket.api.Session
- import org.eclipse.jetty.websocket.api.StatusCode
- import org.eclipse.jetty.websocket.api.annotations.*
- import java.util.concurrent.CountDownLatch
- import java.util.concurrent.Future
- import java.util.concurrent.TimeUnit
- /**
- * Basic Echo Client Socket
- */
- @WebSocket(maxTextMessageSize = 64 * 1024)
- open class SimpleEchoSocket {
- private val closeLatch: CountDownLatch
- var session: Session? = null
- @Throws(InterruptedException::class)
- fun awaitClose(duration: Int, unit: TimeUnit?): Boolean {
- return closeLatch.await(duration.toLong(), unit)
- }
- @OnWebSocketClose
- fun onClose(statusCode: Int, reason: String?) {
- System.out.printf("Connection closed: %d - %s%n", statusCode, reason)
- session = null
- closeLatch.countDown() // trigger latch
- }
- @OnWebSocketConnect
- fun onConnect(session: Session) {
- System.out.printf("Got connect: %s%n", session)
- this.session = session
- try {
- var fut: Future<Void?>
- fut = session.remote.sendStringByFuture("Hello")
- fut[2, TimeUnit.SECONDS] // wait for send to complete.
- fut = session.remote.sendStringByFuture("Thanks for the conversation.")
- fut[2, TimeUnit.SECONDS] // wait for send to complete.
- } catch (t: Throwable) {
- t.printStackTrace()
- }
- }
- @OnWebSocketMessage
- fun onMessage(msg: String) {
- System.out.printf("Got msg: %s%n", msg)
- if (msg.contains("Thanks")) {
- session!!.close(StatusCode.NORMAL, "I'm done")
- }
- }
- @OnWebSocketError
- fun onError(cause: Throwable) {
- print("WebSocket Error: ")
- cause.printStackTrace(System.out)
- }
- init {
- closeLatch = CountDownLatch(1)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement