Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

java.net.ConnectException (Not triggering the request in wallet) #52

Open
kashifahmad662 opened this issue Oct 28, 2021 · 0 comments
Open

Comments

@kashifahmad662
Copy link

This is output of debug on running the app

[java.net.ConnectException: Failed to connect to bridge.walletconnect.org/2606:4700:20::ac43:45b8:7737, java.net.ConnectException: Failed to connect to bridge.walletconnect.org/2606:4700:20::681a:32c:7737, java.net.ConnectException: Failed to connect to bridge.walletconnect.org/2606:4700:20::681a:22c:7737, java.net.SocketTimeoutException: failed to connect to bridge.walletconnect.org/104.26.2.44 (port 7737) from /192.168.1.8 (port 44900) after 10000ms, java.net.SocketTimeoutException: failed to connect to bridge.walletconnect.org/172.67.69.184 (port 7737) from /192.168.1.8 (port 40876) after 10000ms]

ExampleAplication.kt
`import androidx.multidex.MultiDexApplication
import com.squareup.moshi.Moshi
import com.peepout.io.peepout.server.BridgeServer
import com.squareup.moshi.JsonClass
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.CipherSuite
import okhttp3.TlsVersion
import okhttp3.ConnectionSpec
import android.util.Log
import org.komputing.khex.extensions.toNoPrefixHexString
import org.walletconnect.Session
import org.walletconnect.impls.*
import org.walletconnect.nullOnThrow
import java.io.File
import java.net.InetSocketAddress
import java.net.Proxy
import java.util.*

class ExampleApplication:MultiDexApplication() {

@JsonClass(generateAdapter = true)
override fun onCreate() {
    super.onCreate()
    initMoshi()
    initClient()
    initBridge()
    initSessionStorage()
}

private fun initClient() {


    client = OkHttpClient.Builder().build()
}

private fun initMoshi() {
    moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
}


private fun initBridge() {
    bridge = BridgeServer(moshi)
    bridge.start()
}

private fun initSessionStorage() {
    storage = FileWCSessionStore(File(cacheDir, "session_store.json").apply { createNewFile() }, moshi)
}

companion object {
    private lateinit var client: OkHttpClient
    private lateinit var moshi: Moshi
    private lateinit var bridge: BridgeServer
    private lateinit var storage: WCSessionStore
    lateinit var config: Session.Config
    lateinit var session: Session

    fun resetSession() {
        nullOnThrow { session }?.clearCallbacks()
        val key = ByteArray(32).also { Random().nextBytes(it) }.toNoPrefixHexString()
        Log.d("Kashif",BridgeServer.PORT.toString())
        config = Session.Config(UUID.randomUUID().toString(), "https://bridge.walletconnect.org", key)
        session = WCSession(config, MoshiPayloadAdapter(moshi), storage,
            OkHttpTransport.Builder(client, moshi),
            Session.PeerMeta(name = "Peepout"))
        session.offer() }
}

}BridgeServer:import android.util.Log
import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import org.java_websocket.WebSocket
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.server.WebSocketServer
import java.lang.Exception
import java.lang.ref.WeakReference
import java.net.InetSocketAddress
import java.util.*
import java.util.concurrent.ConcurrentHashMap

class BridgeServer(moshi: Moshi) : WebSocketServer(InetSocketAddress(PORT)) {
@JsonClass(generateAdapter = true)

private val adapter = moshi.adapter<Map<String, String>>(

    Types.newParameterizedType(
        Map::class.java,
        String::class.java,
        String::class.java
    )
)

private val pubs: MutableMap<String, MutableList<WeakReference<WebSocket>>> = ConcurrentHashMap()
private val pubsLock = Any()
private val pubsCache: MutableMap<String, String?> = ConcurrentHashMap()

override fun onOpen(conn: WebSocket?, handshake: ClientHandshake?) {
    Log.d("Kashif",PORT.toString())
    Log.d("#####", "onOpen: ${conn?.remoteSocketAddress?.address?.hostAddress}")
}

override fun onClose(conn: WebSocket?, code: Int, reason: String?, remote: Boolean) {
    Log.d("#####", "onClose: ${conn?.remoteSocketAddress?.address?.hostAddress}")
    conn?.let { cleanUpSocket(it) }
}

override fun onMessage(conn: WebSocket?, message: String?) {


    Log.d("#####", "Message: $message")
    var check = message
    check =check?.replace("true","\"true\"")

    try {
        conn ?: error("Unknown socket")
        check?.also {
            val msg = adapter.fromJson(it) ?: error("Invalid message")//error
            val type: String = msg["type"] ?: error("Type not found")
            val topic: String = msg["topic"] ?: error("Topic not found")

            when (type) {
                "pub" -> {

                    var sendMessage = false
                    pubs[topic]?.forEach { r ->
                        r.get()?.apply {
                            send(check)
                            sendMessage = true
                        }
                    }
                    if (!sendMessage) {
                        Log.d("#####", "Cache message: $check")
                        pubsCache[topic] = check
                    }
                }
                "sub" -> {

                    pubs.getOrPut(topic, { mutableListOf() }).add(WeakReference(conn))
                    pubsCache[topic]?.let { cached ->
                        Log.d("#####", "Send cached: $cached")
                        conn.send(cached)
                    }

                }
                else -> error("Unknown type")
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

override fun onStart() {
    Log.d("#####", "Server started")
    connectionLostTimeout = 1000000000
}

override fun onError(conn: WebSocket?, ex: Exception?) {
    Log.d("#####", "onError")
    ex?.printStackTrace()
    conn?.let { cleanUpSocket(it) }
}

private fun cleanUpSocket(conn: WebSocket) {
    synchronized(pubsLock) {
        pubs.forEach {
            it.value.removeAll { r -> r.get().let { v -> v == null || v == conn } }
        }
    }
}

companion object {
    val PORT = 5000 + Random().nextInt(60000)

}

}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant