Advertisement
karpach3000

Untitled

Dec 2nd, 2019
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. package com.its
  2.  
  3. import org.eclipse.jetty.websocket.api.Session
  4. import org.eclipse.jetty.websocket.api.StatusCode
  5. import org.eclipse.jetty.websocket.api.annotations.*
  6. import java.util.concurrent.CountDownLatch
  7. import java.util.concurrent.Future
  8. import java.util.concurrent.TimeUnit
  9.  
  10.  
  11. /**
  12. * Basic Echo Client Socket
  13. */
  14. @WebSocket(maxTextMessageSize = 64 * 1024)
  15. open class SimpleEchoSocket {
  16. private val closeLatch: CountDownLatch
  17. var session: Session? = null
  18. @Throws(InterruptedException::class)
  19. fun awaitClose(duration: Int, unit: TimeUnit?): Boolean {
  20. return closeLatch.await(duration.toLong(), unit)
  21. }
  22.  
  23. @OnWebSocketClose
  24. fun onClose(statusCode: Int, reason: String?) {
  25. System.out.printf("Connection closed: %d - %s%n", statusCode, reason)
  26. session = null
  27. closeLatch.countDown() // trigger latch
  28. }
  29.  
  30. @OnWebSocketConnect
  31. fun onConnect(session: Session) {
  32. System.out.printf("Got connect: %s%n", session)
  33. this.session = session
  34. try {
  35. var fut: Future<Void?>
  36. fut = session.remote.sendStringByFuture("Hello")
  37. fut[2, TimeUnit.SECONDS] // wait for send to complete.
  38. fut = session.remote.sendStringByFuture("Thanks for the conversation.")
  39. fut[2, TimeUnit.SECONDS] // wait for send to complete.
  40. } catch (t: Throwable) {
  41. t.printStackTrace()
  42. }
  43. }
  44.  
  45. @OnWebSocketMessage
  46. fun onMessage(msg: String) {
  47. System.out.printf("Got msg: %s%n", msg)
  48. if (msg.contains("Thanks")) {
  49. session!!.close(StatusCode.NORMAL, "I'm done")
  50. }
  51. }
  52.  
  53. @OnWebSocketError
  54. fun onError(cause: Throwable) {
  55. print("WebSocket Error: ")
  56. cause.printStackTrace(System.out)
  57. }
  58.  
  59. init {
  60. closeLatch = CountDownLatch(1)
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement