Skip to content

Instantly share code, notes, and snippets.

@jcollins-g
Forked from devoncarew/index.html
Last active October 19, 2018 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcollins-g/cb9b199b1085873de191e32a1dd5ca4f to your computer and use it in GitHub Desktop.
Save jcollins-g/cb9b199b1085873de191e32a1dd5ca4f 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';
void main() {
var wsTest = WebSocketTest('wss://echo.websocket.org');
InputElement input = querySelector('input');
input.onChange.listen((_) {
wsTest.send(input.value);
input.value = '';
});
}
class WebSocketTest {
final WebSocket _socket;
final _timer = Stopwatch()..start();
WebSocketTest(String url) : _socket = WebSocket(url) {
print('Connecting to $url...');
_startListening();
}
void send(String value) {
print('==> $value');
_socket.send(value);
_timer.reset();
}
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((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