如何在Android中使用socket.io连接Web套接字协议

时间:2018-12-19 09:52:11

标签: android websocket socket.io

我正在尝试使用socket.io在服务器和应用程序之间建立通信。但是它表明socket.io无法连接到具有ws协议的服务器。

我的服务器网址类似于->

ws://dev1.geobit.siliconorchard.com:3366/socket.io/?EIO=4&transport=websocket

我的代码是:

private Socket mSocket;

{
    try {
        IO.Options opts = new IO.Options();
        opts.transports = new String[]{ WebSocket.NAME};
        mSocket = IO.socket(new URI(Constant.WEB_SOCKET),opts);

    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

public Socket getSocket() {
    return mSocket;
}

这显示

错误
  

“ java.lang.RuntimeException:无法实例化应用程序com.dev.quras.application.QurasApplication:java.lang.RuntimeException:java.net.URISyntaxException:未知协议:ws:ws://dev1.geobit.siliconorchard .com:3366 / socket.io /?EIO = 4&transport = websocket“

有人可以帮助我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我为此使用Okhttp:

-keep class android.support.test.internal** { *; }
-keep class org.junit.** { *; }
-keep @com.google.common.annotations.VisibleForTesting class *

-keepclasseswithmembers class * {
  @com.google.common.annotations.VisibleForTesting *;
}

然后,您可以像这样启动网络套接字:

@VisibleForTesting

Listener类示例:

private fun loggingInterceptor(): HttpLoggingInterceptor =
        HttpLoggingInterceptor(HttpLoggingInterceptor
                .Logger { message -> Timber.tag("OkHttp").d(message) })
                .setLevel(HttpLoggingInterceptor.Level.BODY)

private val okHttp = OkHttpClient.Builder()
        .connectTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(300, TimeUnit.SECONDS)
        .addInterceptor(loggingInterceptor())
        .readTimeout(60, TimeUnit.SECONDS)
        .build()