|
| 1 | +// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package com.example.ok_http |
| 6 | + |
| 7 | +import okhttp3.Response |
| 8 | +import okhttp3.WebSocket |
| 9 | +import okhttp3.WebSocketListener |
| 10 | +import okio.ByteString |
| 11 | + |
| 12 | +/** |
| 13 | + * `OkHttp` expects a subclass of the abstract class [`WebSocketListener`](https://square.github.io/okhttp/5.x/okhttp/okhttp3/-web-socket-listener/index.html) |
| 14 | + * to be passed to the `newWebSocket` method. |
| 15 | + * |
| 16 | + * `package:jnigen` does not support the ability to subclass abstract Java classes in Dart |
| 17 | + * (see https://github.com/dart-lang/jnigen/issues/348). |
| 18 | + * |
| 19 | + * This file provides an interface `WebSocketListener`, which can |
| 20 | + * be implemented in Dart and a wrapper class `WebSocketListenerProxy`, which |
| 21 | + * can be passed to the OkHttp API. |
| 22 | + */ |
| 23 | +class WebSocketListenerProxy(private val listener: WebSocketListener) : WebSocketListener() { |
| 24 | + interface WebSocketListener { |
| 25 | + fun onOpen(webSocket: WebSocket, response: Response) |
| 26 | + fun onMessage(webSocket: WebSocket, text: String) |
| 27 | + fun onMessage(webSocket: WebSocket, bytes: ByteString) |
| 28 | + fun onClosing(webSocket: WebSocket, code: Int, reason: String) |
| 29 | + fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) |
| 30 | + } |
| 31 | + |
| 32 | + override fun onOpen(webSocket: WebSocket, response: Response) { |
| 33 | + listener.onOpen(webSocket, response) |
| 34 | + } |
| 35 | + |
| 36 | + override fun onMessage(webSocket: WebSocket, text: String) { |
| 37 | + listener.onMessage(webSocket, text) |
| 38 | + } |
| 39 | + |
| 40 | + override fun onMessage(webSocket: WebSocket, bytes: ByteString) { |
| 41 | + listener.onMessage(webSocket, bytes) |
| 42 | + } |
| 43 | + |
| 44 | + override fun onClosing(webSocket: WebSocket, code: Int, reason: String) { |
| 45 | + listener.onClosing(webSocket, code, reason) |
| 46 | + } |
| 47 | + |
| 48 | + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { |
| 49 | + listener.onFailure(webSocket, t, response) |
| 50 | + } |
| 51 | +} |
0 commit comments