我想知道是否有 Scarlet Web 套接字库的 Java 实现。
@EchoBotScope
@Component(modules = [(EchoBotComponent.EchoBotModule::class)], dependencies = [(EchoBotComponent.Dependency::class)])
interface EchoBotComponent {
fun inject(echoBotFragment: EchoBotFragment)
interface Dependency {
fun application(): Application
}
@Component.Builder
interface Builder {
fun dependency(dependency: Dependency): Builder
fun build(): EchoBotComponent
}
@Module
class EchoBotModule {
@Provides
@EchoBotScope
fun provideOkHttpClient(): OkHttpClient = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.build()
@Provides
@EchoBotScope
fun provideLifecycle(application: Application, loggedInLifecycle: LoggedInLifecycle): Lifecycle =
AndroidLifecycle.ofApplicationForeground(application)
.combineWith(loggedInLifecycle)
@Provides
@EchoBotScope
fun provideEchoService(client: OkHttpClient, lifecycle: Lifecycle): EchoService {
val scarlet = Scarlet.Builder()
.webSocketFactory(client.newWebSocketFactory("wss://demos.kaazing.com/echo"))
.lifecycle(lifecycle)
.addMessageAdapterFactory(BitmapMessageAdapter.Factory())
.addStreamAdapterFactory(RxJava2StreamAdapterFactory())
.build()
return scarlet.create()
}
}
interface ComponentProvider {
val echoBotComponent: EchoBotComponent
}
}
如何自定义演示应用程序来制作我自己的 okhttp WebSocket 客户端?
最佳答案
我在这里假设您想在java项目中使用scarlet。首先,您使用的版本已经过时。请查找scarlet库最新版本here 。它具有重大更改,您将需要迁移代码。
您可以在java项目中按原样使用scarlet库,而不依赖于kotlin特定模块,例如scarlet-stream-adapter-coroutines
。下面给出了 Java 中的 EchoBotModule
实现示例。
@Module
class EchoBotModule {
@Provides
@EchoBotScope
OkHttpClient provideOkHttpClient() {
return OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BASIC))
.build();
}
@Provides
@EchoBotScope
Lifecycle provideLifecycle(Application application, LoggedInLifecycle loggedInLifecycle) {
return AndroidLifecycle.ofApplicationForeground(application)
.combineWith(loggedInLifecycle);
}
@Provides
@EchoBotScope
EchoService provideEchoService(OkHttpClient client, Lifecycle lifecycle) {
Protocol pr = new OkHttpWebSocket(client, new OkHttpWebSocket.SimpleRequestFactory(
() -> new Request.Builder().url("wss://demos.kaazing.com/echo").build(),
() -> ShutdownReason.GRACEFUL
));
List<MessageAdapter.Factory> messageAdapterFactories = Collections.singletonList(new BitmapMessageAdapter.Factory());
List<StreamAdapter.Factory> streamAdapterFactories = Collections.singletonList(new RxJava2StreamAdapterFactory());
Scarlet.Configuration configuration = new Scarlet.Configuration(lifecycle, null, streamAdapterFactories, messageAdapterFactories, false);
Scarlet scarlet = new Scarlet(pr, configuration);
return scarlet.create();
}
}
关于kotlin - 如何在Java中使用okhttp实现scarlet websocket库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54784410/