Last active
May 15, 2018 10:43
-
-
Save PDDStudio/a3b03029bb4e0727bd603a151ec2d838 to your computer and use it in GitHub Desktop.
Dart infinity keep-alive WebSocket sample (https://dartpad.dartlang.org/a3b03029bb4e0727bd603a151ec2d838)
This file contains 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
<!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> |
This file contains 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
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); | |
} | |
} |
This file contains 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
#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