Skip to content

Instantly share code, notes, and snippets.

@devoncarew
Last active October 19, 2018 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save devoncarew/479ecba5a56fd706b648 to your computer and use it in GitHub Desktop.
Save devoncarew/479ecba5a56fd706b648 to your computer and use it in GitHub Desktop.
WebSocket test
<!-- Copyright 2015 the Dart project authors. All rights reserved.
Use of this source code is governed by a BSD-style license
that can be found in the LICENSE file. -->
<h2>A WebSocket test using echo.websocket.org</h2>
<br>
<p>Enter text to echo:</p>
<input type="text">
// Copyright 2012 the Dart project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
import 'dart:html';
const echoUrl = 'wss://echo.websocket.org';
void main() {
WebSocketTest wsTest = new WebSocketTest(echoUrl);
InputElement input = querySelector('input');
input.onChange.listen((_) {
wsTest.send(input.value);
input.value = '';
});
}
class WebSocketTest {
WebSocket _socket;
Stopwatch _timer;
WebSocketTest(String url) {
print("Connecting to ${url}…");
_socket = new WebSocket(url);
_startListening();
}
void send(String value) {
print('==> ${value}');
_socket.send(value);
_timer = new Stopwatch()..start();
}
void _startListening() {
_socket.onOpen.listen((e) {
print('Connected!');
send('Hello from Dart!');
});
_socket.onClose.listen((_) => print('Websocket closed.'));
_socket.onError.listen((_) => print("Error opening connection."));
_socket.onMessage.listen((MessageEvent e) {
print('<== ${e.data} [${_timer.elapsedMilliseconds}ms]');
});
}
}
/* Copyright 2015 the Dart project authors. All rights reserved. */
/* Use of this source code is governed by a BSD-style license */
/* that can be found in the LICENSE file. */
input {
width: 250px;
margin-left: 2em;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment