Skip to content

Instantly share code, notes, and snippets.

@ggirou
Last active August 29, 2015 14:07
Show Gist options
  • Save ggirou/d7ac5d1c7ac88ddde394 to your computer and use it in GitHub Desktop.
Save ggirou/d7ac5d1c7ac88ddde394 to your computer and use it in GitHub Desktop.
Websocket Dart server
version: 1
runtime: custom
vm: true
api_version: 1
manual_scaling:
instances: 1
import 'dart:io';
import 'dart:async';
var content = '''<html>
<head>
<script type="application/javascript">
var output = function(data) { document.write(data + "<br>"); };
var socket = new WebSocket("ws://" + location.host + "/ws");
socket.onopen = function(event) {
output('Socket opened');
socket.send("Hello");
socket.send("World!");
};
socket.onmessage = function(event) {
output('Message ' + event.data);
}
</script>
</head>
<body>...</body>
</html>''';
main(List<String> args) {
runZoned(() {
HttpServer.bind(InternetAddress.ANY_IP_V4, 8080).then((HttpServer server) {
print("Listening on ws://localhost:8080/ws");
server.listen((HttpRequest req) {
print(req);
if (req.uri.path == '/ws') {
WebSocketTransformer.upgrade(req).then(handleWebSocket);
} else {
req.response
..headers.add('Content-Type', 'text/html')
..write(content)
..close();
}
});
});
}, onError: (e) => print("An error occurred $e"));
}
void handleWebSocket(WebSocket ws) {
ws.listen((data) => ws.add("PONG: $data"));
}
FROM google/dart-runtime
# Generated by pub
# See http://pub.dartlang.org/doc/glossary.html#lockfile
packages: {}
name: websocket
description: A sample websocket application
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment