Guest User

Untitled

a guest
Feb 22nd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.77 KB | None | 0 0
  1. import org.w3c.dom.MessageEvent
  2. import org.w3c.dom.WebSocket
  3. import kotlin.browser.window
  4.  
  5. class KWebSocketImpl(val url : String, val reconnectDelayMillis: Int, val listener : (dynamic) -> Unit) {
  6. private var currentSocket : WebSocket? = null
  7. private val queue = arrayListOf<String>()
  8. private var closed = false
  9.  
  10. init {
  11. connect()
  12. }
  13.  
  14. fun stop() {
  15. closed = true
  16. try {
  17. currentSocket?.close()
  18. } catch (ignore : Throwable) {
  19. currentSocket = null
  20. }
  21. }
  22.  
  23. fun send(o: Any) {
  24. if (closed) {
  25. throw IllegalStateException("Socket already stopped")
  26. }
  27.  
  28. val text = JSON.stringify(o)
  29. queue.add(text)
  30.  
  31. flush()
  32. }
  33.  
  34. private fun flush() {
  35. val s = currentSocket ?: return
  36.  
  37. try {
  38. val iterator = queue.iterator()
  39. while (iterator.hasNext()) {
  40. val text = iterator.next()
  41.  
  42. s.send(text)
  43.  
  44. iterator.remove()
  45. }
  46. } catch (ignore : Throwable) {
  47. }
  48. }
  49.  
  50. private fun onMessage(message : dynamic) {
  51. listener(message)
  52. }
  53.  
  54. private fun reconnectWithDelay() {
  55. window.setTimeout({
  56. connect()
  57. }, reconnectDelayMillis)
  58. }
  59.  
  60. private fun connect() {
  61. try {
  62. tryConnect()
  63. } catch (any : Throwable) {
  64. reconnectWithMessageAndDelay()
  65. }
  66. }
  67.  
  68. private fun reconnectWithMessageAndDelay() {
  69. console.error("WebSocket ($url) connection failure, will reconnect in ${reconnectDelayMillis / 1000.0}s")
  70. reconnectWithDelay()
  71. }
  72.  
  73. private fun tryConnect() {
  74. val socket = WebSocket(url)
  75. fun closeSocket() {
  76. try {
  77. currentSocket?.close()
  78. socket.close()
  79. } finally {
  80. currentSocket = null
  81. }
  82. }
  83.  
  84. socket.onopen = {
  85. if (currentSocket !== socket) {
  86. currentSocket?.close()
  87. currentSocket = socket
  88. }
  89.  
  90. window.setTimeout({
  91. flush()
  92. }, 0)
  93. }
  94.  
  95. socket.onerror = {
  96. closeSocket()
  97. reconnectWithMessageAndDelay()
  98. }
  99.  
  100. socket.onmessage = {
  101. if (it is MessageEvent) {
  102. val data = it.data
  103. console.log("Received from websocket", data)
  104. if (data is String) {
  105. onMessage(JSON.parse(data))
  106. }
  107.  
  108. flush()
  109. }
  110. }
  111.  
  112. socket.onclose = {
  113. if (socket === currentSocket) {
  114. currentSocket = null
  115. }
  116.  
  117. if (!closed) {
  118. tryConnect()
  119. }
  120. }
  121. }
  122. }
Add Comment
Please, Sign In to add comment