Android application cannot connect to socket.io Golang server
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!

In Go programming, ways to effectively manage errors include: 1) using error values instead of exceptions, 2) using error wrapping techniques, 3) defining custom error types, 4) reusing error values for performance, 5) using panic and recovery with caution, 6) ensuring that error messages are clear and consistent, 7) recording error handling strategies, 8) treating errors as first-class citizens, 9) using error channels to handle asynchronous errors. These practices and patterns help write more robust, maintainable and efficient code.

Implementing concurrency in Go can be achieved by using goroutines and channels. 1) Use goroutines to perform tasks in parallel, such as enjoying music and observing friends at the same time in the example. 2) Securely transfer data between goroutines through channels, such as producer and consumer models. 3) Avoid excessive use of goroutines and deadlocks, and design the system reasonably to optimize concurrent programs.

Gooffersmultipleapproachesforbuildingconcurrentdatastructures,includingmutexes,channels,andatomicoperations.1)Mutexesprovidesimplethreadsafetybutcancauseperformancebottlenecks.2)Channelsofferscalabilitybutmayblockiffullorempty.3)Atomicoperationsareef

Go'serrorhandlingisexplicit,treatingerrorsasreturnedvaluesratherthanexceptions,unlikePythonandJava.1)Go'sapproachensureserrorawarenessbutcanleadtoverbosecode.2)PythonandJavauseexceptionsforcleanercodebutmaymisserrors.3)Go'smethodpromotesrobustnessand

WhentestingGocodewithinitfunctions,useexplicitsetupfunctionsorseparatetestfilestoavoiddependencyoninitfunctionsideeffects.1)Useexplicitsetupfunctionstocontrolglobalvariableinitialization.2)Createseparatetestfilestobypassinitfunctionsandsetupthetesten

Go'serrorhandlingreturnserrorsasvalues,unlikeJavaandPythonwhichuseexceptions.1)Go'smethodensuresexpliciterrorhandling,promotingrobustcodebutincreasingverbosity.2)JavaandPython'sexceptionsallowforcleanercodebutcanleadtooverlookederrorsifnotmanagedcare

AneffectiveinterfaceinGoisminimal,clear,andpromotesloosecoupling.1)Minimizetheinterfaceforflexibilityandeaseofimplementation.2)Useinterfacesforabstractiontoswapimplementationswithoutchangingcallingcode.3)Designfortestabilitybyusinginterfacestomockdep

Centralized error handling can improve the readability and maintainability of code in Go language. Its implementation methods and advantages include: 1. Separate error handling logic from business logic and simplify code. 2. Ensure the consistency of error handling by centrally handling. 3. Use defer and recover to capture and process panics to enhance program robustness.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
