3 ms·
Not if the application has the right permissions on their installation manifest. <uses-permission android:name="android.permission.INTERNET" /> Then you need
by pjmlp 3mo ago
Not if the application has the right permissions on their installation manifest.
<uses-permission android:name="android.permission.INTERNET" />
Then you need to write the server handling code on a background application thread, with perfectly working server sockets.
This only works on wlan, or local network when using bluethooth, but who wants data modem for a server anyway.
With Gemini's compliment,
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.ServerSocket
import java.net.Socket
import java.net.SocketException
class AndroidTcpServer {
private var serverSocket: ServerSocket? = null
private var isRunning = false
// Call this function from a CoroutineScope (e.g., lifecycleScope.launch)
async suspend fun startServer(port: Int = 8080) {
withContext(Dispatchers.IO) {
try {
serverSocket = ServerSocket(port)
isRunning = true
// Loop to continuously accept incoming client connections
while (isRunning) {
val clientSocket = serverSocket?.accept() // Blocks until a client connects
if (clientSocket != null) {
// Handle each client connection in a separate background routine
handleClient(clientSocket)
}
}
} catch (e: SocketException) {
// Triggered when stopServer() closes the socket
println("Server socket closed: ${e.message}")
} catch (e: Exception) {
e.printStackTrace()
} finally {
stopServer()
}
}
}
private suspend fun handleClient(socket: Socket) {
withContext(Dispatchers.IO) {
try {
val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
val outputStream = socket.getOutputStream()
// Read incoming text from client
val incomingMessage = reader.readLine()
println("Received from client: $incomingMessage")
// Send a simple response back to the client
val response = "Hello from Android Server!\n"
outputStream.write(response.toByteArray())
outputStream.flush()
} catch (e: Exception) {
e.printStackTrace()
} finally {
// Always close individual client connections
socket.close()
}
}
}
fun stopServer() {
isRunning = false
try {
serverSocket?.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
As you might imagine by my comment history, I am a big fan of letting Android be Android, with Android native apps, not stuffing GNU/Linux into an APK.