• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (C) 2025 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17import {FunctionUtils} from 'common/function_utils';
18import {TimeUtils} from 'common/time/time_utils';
19
20export type ErrorListener = (msg: string) => Promise<void>;
21
22export abstract class WebSocketStream {
23  constructor(protected sock: WebSocket) {
24    sock.binaryType = 'arraybuffer';
25    sock.onclose = () => this.onClose();
26  }
27
28  abstract connect(): Promise<void>;
29
30  protected onError: ErrorListener = FunctionUtils.DO_NOTHING_ASYNC;
31  protected onClose: () => void = FunctionUtils.DO_NOTHING;
32
33  async write(data: string | Uint8Array): Promise<void> {
34    await TimeUtils.wait(() => this.isOpen());
35    this.sock.send(data);
36  }
37
38  close(): void {
39    this.sock.close();
40  }
41
42  isOpen(): boolean {
43    return this.sock.readyState === WebSocket.OPEN;
44  }
45}
46