Skip to content

Instantly share code, notes, and snippets.

@kevmoo
Forked from devoncarew/index.html
Created October 2, 2018 20:10
Show Gist options
  • Save kevmoo/e21056df19885600344a4d453fa01911 to your computer and use it in GitHub Desktop.
Save kevmoo/e21056df19885600344a4d453fa01911 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