Skip to content

Instantly share code, notes, and snippets.

@PDDStudio
Last active May 15, 2018 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PDDStudio/a3b03029bb4e0727bd603a151ec2d838 to your computer and use it in GitHub Desktop.
Save PDDStudio/a3b03029bb4e0727bd603a151ec2d838 to your computer and use it in GitHub Desktop.
Dart infinity keep-alive WebSocket sample (https://dartpad.dartlang.org/a3b03029bb4e0727bd603a151ec2d838)
<!DOCTYPE html>
<html>
<head>
<title>A Minimalist App</title>
<script defer src="main.dart.js"></script>
</head>
<body>
<p id="RipVanWinkle">
RipVanWinkle paragraph.
</p>
<div>
<li id="ListItems">
<ul>Item 1</ul>
<ul>Item 2</ul>
</li>
</div>
</body>
</html>
import 'dart:html';
import 'dart:async';
void main() {
querySelector('#RipVanWinkle').text = 'Content Text set via Dart!';
new Connection(window.document);
}
class Connection {
WebSocket _ws;
Document _doc;
Connection(Document doc) {
this._doc = doc;
this.initConnection();
}
void initConnection() {
this._ws = new WebSocket('wss://echo.websocket.org');
this._ws.onOpen.listen((e) {
this.addOutputLine('Connected!');
this._ws.send('Hello from Dart!');
});
this._ws.onMessage.listen((MessageEvent msg) {
this.addOutputLine('Received Data: ${msg.data}');
this.schedulePingTrigger();
});
}
void schedulePingTrigger() {
new Timer(new Duration(milliseconds: 1000), () {
this._ws.send('Pinging for Connection Keep-Alive! (1000ms)');
});
}
void addOutputLine(String value) {
var elem = new Element.ul();
elem.text = value;
this._doc.querySelector('#ListItems').children.add(elem);
}
}
#RipVanWinkle {
font-size: 20px;
font-family: 'Open Sans', sans-serif;
text-align: center;
margin-top: 20px;
background-color: SlateBlue;
color: Yellow;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment