Last active
May 28, 2018 09:15
-
-
Save manveru/476ae18969ea95f1131b78bab5afc78d to your computer and use it in GitHub Desktop.
WebSocket in Mint
This file contains hidden or 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
record Provider.WebSocket.Subscription { | |
endpoint : Url, | |
message : Function(Html.Event, Void), | |
open : Function(Html.Event, Void), | |
error : Function(Html.Event, Void) | |
} | |
provider Provider.WebSocket : Provider.WebSocket.Subscription { | |
fun attach : Void { | |
` | |
(() => { | |
this.subscriptions.forEach((subscription) => { | |
const url = subscription.endpoint.origin + subscription.endpoint.path | |
const open = this[url + "_open"] || (this[url + "_open"] = subscription.open.bind(this)) | |
const message = this[url + "_message"] || (this[url + "_message"] = subscription.message.bind(this)) | |
const error = this[url + "_error"] || (this[url + "_error"] = subscription.error.bind(this)) | |
var socket | |
var interval = 1000 // make exponential backoff | |
const socketCloseListener = (event) => { | |
if (socket) { console.error("Reconnecting WebSocket") } | |
socket = new WebSocket(url) | |
socket.addEventListener("close", () => setTimeout(socketCloseListener, interval)) | |
socket.addEventListener("open", open) | |
socket.addEventListener("message", message) | |
socket.addEventListener("error", error) | |
} | |
socketCloseListener() | |
}) | |
})() | |
` | |
} | |
fun detach : Void { | |
` | |
socket.close(1000, "socket detached") | |
` | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment