Skip to content

Instantly share code, notes, and snippets.

@azenla
Created December 10, 2015 23:33
Show Gist options
  • Save azenla/d54c6489f41052a8f666 to your computer and use it in GitHub Desktop.
Save azenla/d54c6489f41052a8f666 to your computer and use it in GitHub Desktop.
import "dart:async";
import "dart:io";
import "dart:convert";
main(List<String> args) async {
if (args.isEmpty) {
args = ["--server"];
}
if (args[0] == "--server") {
await createServer();
} else {
await createClient();
}
}
createServer() async {
var baseData = {
"method": "set",
"path": "/downstream/REST/test",
"value": "Hello",
"rid": 40
};
Map sendData = {
"requests": new List<Map>.generate(1000, (i) => baseData),
"msg": 1
};
var server = await HttpServer.bind("0.0.0.0", 9540);
var i = 1;
await for (HttpRequest request in server) {
var id = i++;
if (!(await WebSocketTransformer.isUpgradeRequest(request))) {
request.response
..statusCode = HttpStatus.BAD_REQUEST
..writeln("Bad Request.")
..close();
continue;
}
WebSocket socket = await WebSocketTransformer.upgrade(request);
int sent = 0;
int received = 0;
socket.listen((data) {
if (data is String) {
var json = const JsonDecoder().convert(data);
received++;
}
});
Timer timerA;
Timer timerB;
schedule([Duration duration = Duration.ZERO]) {
timerA = new Timer(duration, () {
socket.add(const JsonEncoder().convert(sendData));
if ((sent - received) > 100) {
schedule(const Duration(milliseconds: 1));
} else {
schedule();
}
sent++;
});
}
int _lastSent = 0;
int _lastReceived = 0;
timerB = new Timer.periodic(const Duration(seconds: 1), (_) {
var haveSent = sent - _lastSent;
var haveReceived = received - _lastReceived;
print("Client #${id}: Sent: ${haveSent}, Received: ${haveReceived}");
_lastSent = sent;
_lastReceived = received;
});
socket.done.then((_) {
if (timerA != null) {
timerA.cancel();
}
if (timerB != null) {
timerB.cancel();
}
});
await schedule();
}
}
createClient() async {
var socket = await WebSocket.connect("ws://127.0.0.1:9540/ws");
await for (var msg in socket) {
if (msg is String) {
var data = const JsonDecoder().convert(msg);
socket.add(const JsonEncoder().convert(data));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment