I have Android service and this service stay as ServerSocket
and reading message from client than response them via socket connection
I start server socket port 5000 in one Thread
then in that one i accept clients and reading messages.
My problem starts here . When i’m reading message sometimes my .read()
function waiting until forever and i cannot read message.
What can i do?
Here my code
var serverSocket: ServerSocket?=null
fun startService() {//Where i start Android service
val server = ClientHandler()
Thread(server).start()
}
internal inner class ClientHandler() : Runnable { //Where i start Socket server
override fun run() {
try {
serverSocket = ServerSocket(5000)
while (true) {
val socket: Socket = serverSocket!!.accept()
socket.reuseAddress = true
ServerThread(socket).start()
}
}catch (e: ConnectException) {
_logEx("UnExpected connection error", e)
}
catch (ex: IOException) {
_logEx("ClientHandler", ex)
}
catch (e: Exception){
_logEx("ServerSocketHandler ", e)
}
}
}
internal inner class ServerThread(socket: Socket) : Thread() {
private var client: Socket = socket
private val writer = PrintStream(client.getOutputStream())
private var receiveString: String = ""
override fun run() {
try {
_log("serversocket isclosed : ${serverSocket?.isClosed}")
_log("socket isclosed : ${client.isClosed}")
_log("Starting to read message")
val inputStream = client.getInputStream()
val byteArrayOutputStream = ByteArrayOutputStream(2048)
val buffer = ByteArray(2048)
var bytesRead: Int
while (true) {
bytesRead = inputStream.read(buffer)//Sometimes cannot read message and stays until forever
if (bytesRead == -1) {
break
}
byteArrayOutputStream.reset()
byteArrayOutputStream.write(buffer, 0, bytesRead)
receiveString = byteArrayOutputStream.toString()
checkMessage(receiveString,writer)
}
} catch (ex: Exception) {
_log("Cannot read the message. Please try again")
val spReq = Error()
spReq.sendErrorMsg(writer, "Cannot read the message. Please try again")
}
}
}