Reputation: 41
I have created a Python server that communicates with an Android client using sockets. Now I'm trying to implement error handling in case of server disconnection.
Initially, the client is connected to the socket, but after a forced server interruption occurs, I want the client to automatically try to reconnect to the server and wait until it becomes available again.
When the server is restarted, the reconnection happens successfully. However, when the while (running)
loop is restarted, a ConnectionResetException
is thrown at the line bytesRead = dataInputStream.read(buffer)
.
I'm trying to understand how to handle this exception, and I'm not sure if it depends solely on the client side. Any clues?
private inner class Receiver(private val dataInputStream: DataInputStream) : Thread() {
val dataReceivedListeners = mutableListOf<(ByteArray) -> Unit>()
private var running = true
override fun run() {
val buffer = ByteArray(1024)
var bytesRead: Int
val dataBuilder = StringBuilder()
while (running) {
try {
bytesRead = dataInputStream.read(buffer)
if (bytesRead <= 0) {
break
}
# DATA HANDLING ...
}
catch (e: SocketException){
reconnected = false
var tries = 0
while (tries<5){
if (!reconnected){
reconnect()
tries +=1
Thread.sleep(1000)
}
else {
break
}
}
if (tries >= 5 && !reconnected) {
Log.d("Reconnection failed", "All reconnection attempts failed")
break
}
}
}
}
}
var reconnected = true
private fun reconnect() {
// Close the current connection
try {
client?.close()
client = null
sender = null
receiver = null
client = Socket()
val address = InetSocketAddress("192.168.***.***", 8888)
client!!.connect(address, 20000)
// Update the sender and receiver with new streams
val outputStream = client?.getOutputStream()
val inputStream = client?.getInputStream()
sender = Sender(DataOutputStream(outputStream))
receiver = Receiver(DataInputStream(inputStream))
receiver?.dataReceivedListeners?.add { data ->
dataReceivedListeners.forEach { listener ->
listener(data)
}
}
receiver?.start()
reconnected = true
Log.d("Reconnection", "Reconnection happened")
} catch (e: Exception) {
reconnected = false
Log.d("Reconnection failed", "Reconnection has failed")
}
}
}
Upvotes: 0
Views: 168