Last active
August 29, 2015 14:07
-
-
Save ggirou/d7ac5d1c7ac88ddde394 to your computer and use it in GitHub Desktop.
Websocket Dart server
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
version: 1 | |
runtime: custom | |
vm: true | |
api_version: 1 | |
manual_scaling: | |
instances: 1 |
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: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")); | |
} |
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
FROM google/dart-runtime |
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
# Generated by pub | |
# See http://pub.dartlang.org/doc/glossary.html#lockfile | |
packages: {} |
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
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