Skip to content

Commit

Permalink
Create a package:web_socket WebSocket from dart:io WebSocket (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
brianquinlan authored Apr 4, 2024
1 parent 5214f76 commit caad9ca
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 1 deletion.
5 changes: 5 additions & 0 deletions pkgs/web_socket/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## 0.1.1

- Add the ability to create a `package:web_socket` `WebSocket` given a
`dart:io` `WebSocket`.

## 0.1.0

- Basic functionality in place.
4 changes: 4 additions & 0 deletions pkgs/web_socket/lib/src/io_web_socket.dart
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ class IOWebSocket implements WebSocket {
return IOWebSocket._(webSocket);
}

// Create an `IOWebSocket` from an existing `dart:io` `WebSocket`.
factory IOWebSocket.fromWebSocket(io.WebSocket webSocket) =>
IOWebSocket._(webSocket);

IOWebSocket._(this._webSocket) {
_webSocket.listen(
(event) {
Expand Down
2 changes: 1 addition & 1 deletion pkgs/web_socket/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ description: >-
Any easy-to-use library for communicating with WebSockets
that has multiple implementations.
repository: https://github.com/dart-lang/http/tree/master/pkgs/web_socket
version: 0.1.0
version: 0.1.1

environment:
sdk: ^3.3.0
Expand Down
40 changes: 40 additions & 0 deletions pkgs/web_socket/test/io_web_socket_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

@TestOn('vm')
library;

import 'dart:io' as io;

import 'package:test/test.dart';
import 'package:web_socket/io_web_socket.dart';
import 'package:web_socket/web_socket.dart';

void main() {
group('fromWebSocket', () {
late final io.HttpServer server;
late io.HttpHeaders headers;
late Uri uri;

setUp(() async {
server = (await io.HttpServer.bind('localhost', 0))
..listen((request) async {
headers = request.headers;
await io.WebSocketTransformer.upgrade(request)
.then((webSocket) => webSocket.listen(webSocket.add));
});
uri = Uri.parse('ws://localhost:${server.port}');
});

test('custom headers', () async {
final ws = IOWebSocket.fromWebSocket(await io.WebSocket.connect(
uri.toString(),
headers: {'fruit': 'apple'}));
expect(headers['fruit'], ['apple']);
ws.sendText('Hello World!');
expect(await ws.events.first, TextDataReceived('Hello World!'));
await ws.close();
});
});
}

0 comments on commit caad9ca

Please sign in to comment.