Home  >  Article  >  Backend Development  >  Android application cannot connect to socket.io Golang server

Android application cannot connect to socket.io Golang server

PHPz
PHPzforward
2024-02-08 21:48:221163browse

Android应用程序无法连接到socket.io Golang服务器

Recently, the problem that some Android applications cannot connect to the socket.io Golang server has attracted widespread attention. PHP editor Xinyi is here to answer the question for everyone. When using the socket.io Golang server, there are some common connection issues that can cause Android applications to fail to connect. First, make sure your Android application and server are on the same network environment and can access each other. Also, check that the server's address and port are set correctly in your code. If the problem persists, you can try using other network debugging tools to check for connection issues, such as Wireshark, etc. Hope these answers can help you solve your problem!

Question content

I don't know if I'm missing something because my kotlin code doesn't find the golang socket server. I did a netstat -ano and port 8000 is already used for tcp, so I think the socket server is running fine. But my Android still can't find it. Both server and emulator are on the same network. This is my code:

//Server (golang)

import (
    "fmt"
    "net/http"

    socketio "github.com/googollee/go-socket.io"
    "github.com/googollee/go-socket.io/engineio"
    "github.com/googollee/go-socket.io/engineio/transport"
    "github.com/googollee/go-socket.io/engineio/transport/polling"
    "github.com/googollee/go-socket.io/engineio/transport/websocket"
)

server := socketio.newserver(&engineio.options{
    transports: []transport.transport{
        &polling.transport{
            checkorigin: alloworiginfunc,
        },
        &websocket.transport{
            checkorigin: alloworiginfunc,
        },
    },
})

server.onconnect("/", func(s socketio.conn) error {
    s.setcontext("")
    fmt.println("connected:", s.id())
    return nil
})

server.onevent("/", "notice", func(s socketio.conn, msg string) {
    fmt.println("notice:", msg)
    s.emit("reply", "have "+msg)
})

server.onerror("/", func(s socketio.conn, e error) {
    fmt.println("meet error:", e)
})

server.ondisconnect("/", func(s socketio.conn, reason string) {
    fmt.println("closed", reason)
})

go server.serve()
defer server.close()

http.handle("/socket.io/", server)
http.handle("/", http.fileserver(http.dir("./asset")))

fmt.println("scktsrv serving at localhost:8000...")
fmt.print(http.listenandserve(":8000", nil))

//android(kotlin)

<uses-permission android:name="android.permission.internet" />

implementation ('io.socket:socket.io-client:2.0.0') {
    exclude group: 'org.json', module: 'json'
}

try {
    msocket = io.socket("http://localhost:8000/skt")
    log.d(tag, "success: ${msocket.id()}")
} catch (e: exception) {
    e.localizedmessage?.let { log.e(tag, it) }
}

msocket.connect()
msocket.on(socket.event_connect, onconnect)
msocket.on("reply", onreply)

private var onconnect = emitter.listener {
    log.i(tag, "onconnect")
    msocket.emit("notice", "{\"relay_num\": 4, \"to_status\": 1}")
}

private var onreply = emitter.listener {
    log.i(tag, "replymsg: ${it[0]}")
}

renew:

Prior to @dev.bmax's answer, I had found some information about enabling cleartexttraffic and had added android:usescleartexttraffic="true" to my androidmanifest.xml , but the application still cannot connect to the server. socket.connected() Now returns false.

Also, how are you supposed to actually connect to the server? Do I just need http://10.0.2.2:8000 without any path?

renew:

I just noticed that I keep getting logs that look like this:

tagsocket(6) with statstag=0xffffffff, statsuid=-1

It keeps popping up on logcat

renew:

I looked around for other codes and found one that works. Fortunately or unfortunately, it's simple. This is the code I found:

//go language

listener, _ := net.listen("tcp", ":8000")
for {
    conn, _ := listener.accept()
    fmt.printf("%s --- %s\n", conn.localaddr(), conn.remoteaddr())
    io.writestring(conn, "welcome to socket")
}

//android kotlin

val host = "192.168.100.250"
val port = 8000

executors.newsinglethreadexecutor().execute {
    try {
        val socket = java.net.socket(host, port)
        receivemove(socket)
    } catch (e: connectexception) {
        log.e(tag, "socket connexc: ${e.localizedmessage}")
        runonuithread {
            toast.maketext(this, "connection failed", toast.length_short).show()
        }
    }catch (e: exception) {
        log.e(tag, "socket connexc: ${e.localizedmessage}")
    }
}

Now I'm wondering, why does the barebones code work, but the code provided by the googollee library doesn't? I don't think I missed any setup on either side.

renew:

Some progress has been made. Found out that the android code works but for some reason is executing some unexpected issues. Here are the details of the changes I made on the android side:

// Application build.gradle

implementation('io.socket:socket.io-client:0.8.3') {
    exclude group: 'org.json', module: 'json'
}

//mainactivity.kt

import io.socket.client.io
import io.socket.client.socket

init {
    try {
        msocket = io.socket("http://<local_ip>:8000/socket.io/")
    }catch (e: connectexception) {
        log.e(tag, "socket connexc: ${e.localizedmessage}")
    }catch (e: urisyntaxexception) {
        log.e(tag, "socket urisynexc: ${e.localizedmessage}")
    }catch (e: exception){
        log.e(tag, "socket exc: ${e.localizedmessage}")
    }
}

// androidmanifest.xml

android:usesCleartextTraffic="true"
//I used to have android:networkSecurityConfig="@xml/network_security_config" here as well

After completing these changes, the application can now connect to the server. But after connecting, the app seems to disconnect immediately. Then it connects to the server again, then disconnects again, then connects to the server, and the cycle doesn't seem to stop. I'm getting lated client namespace disconnect when disconnecting.

SOLUTION

I finally found the part that makes this work. I think the biggest problem is on the android side. Changing the library to use seemed to have fixed all the issues, and then just a small change solved the immediate disconnect issue. Here are the final codes and other details for both parties:

//go language

package main

import (
    "fmt"
    "net/http"

    socketio "github.com/googollee/go-socket.io"
    "github.com/googollee/go-socket.io/engineio"
    "github.com/googollee/go-socket.io/engineio/transport"
    "github.com/googollee/go-socket.io/engineio/transport/polling"
    "github.com/googollee/go-socket.io/engineio/transport/websocket"
)

var alloworiginfunc = func(r *http.request) bool {
    return true
}

func main() {
    server := socketio.newserver(&engineio.options{
        transports: []transport.transport{
            &polling.transport{
                checkorigin: alloworiginfunc,
            },
            &websocket.transport{
                checkorigin: alloworiginfunc,
            },
        },
    })

    server.onconnect("/", func(s socketio.conn) error {
        s.setcontext("")
        fmt.println("connected:", s.id())
        return nil
    })

    server.onevent("/", "notice", func(s socketio.conn, msg string) {
        fmt.println("notice:", msg)
        s.emit("reply", "have "+msg)
    })

    server.onerror("/", func(s socketio.conn, e error) {
        fmt.println("error:", e)
    })

    server.ondisconnect("/", func(s socketio.conn, reason string) {
        fmt.println("closed", reason)
    })

    go server.serve()
    defer server.close()

    http.handle("/socket.io/", server)
    http.handle("/", http.fileserver(http.dir("./asset")))

    fmt.println("socket server serving at localhost:8000...")
    fmt.print(http.listenandserve(":8000", nil))
}

// Android kotlin

androidmanifest.xml

<uses-permission android:name="android.permission.internet" />

<application
    ...
    android:usescleartexttraffic="true">

ApplicationBuild.gradle

implementation('io.socket:socket.io-client:0.8.3') {
        exclude group: 'org.json', module: 'json'
    }

// mainactivity.kt or wherever you want to put this content

import io.socket.client.IO
import io.socket.client.Socket

class MainActivity : AppCompatActivity() {
    private lateinit var mSocket: Socket
    ...
    
    init {
        try {
            mSocket = IO.socket("http://<host>:8000/")
        }catch (e: ConnectException) {
            Log.e(TAG, "Socket ConnExc: ${e.localizedMessage}")
        }catch (e: URISyntaxException) {
            Log.e(TAG, "Socket URISynExc: ${e.localizedMessage}")
        }catch (e: Exception){
            Log.e(TAG, "Socket Exc: ${e.localizedMessage}")
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        mSocket.connect()
        
        binding.btnSend.setOnClickListener {
            Log.i(TAG, "isConnected: ${mSocket.connected()}")
            mSocket.emit("notice", "from_app_msg")
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()

        mSocket.off()
        mSocket.disconnect()
    }
}

Regarding immediate disconnection, it looks like you don't need to add /socket.io when trying to connect on the android side. Removing it solved the disconnection issue. And you don't need the asset folder in your project. Man, this socket.io thing is weird.

The above is the detailed content of Android application cannot connect to socket.io Golang server. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete