I have socket programming and for every client i'm creating new threads and using application with multithreads as in below.
fun ClientHandler() {
try {
var count = 0
var serverSocket = ServerSocket(5000)
while (true) {
val socket: Socket = serverSocket!!.accept()
count
socket.reuseAddress = true
_log("${socket.remoteSocketAddress} Client Connected. Connected client count is $count")
Thread(ServerThread(socket)).start() //Here i'm creating Threads.
}
} 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) : Runnable {
private val client: Socket = socket
private val reader: Scanner = Scanner(client.getInputStream())
private val writer = PrintStream(client.getOutputStream())
private var receiveString: String = ""
override fun run() {
try {
while(reader.hasNextLine()){
receiveString = reader.nextLine() ?: ""
_log("Message received: " receiveString)
if (receiveString != null && receiveString != "") {
checkMessage(receiveString, writer,client)
}
}
} catch (ex: Exception) {
_log("Cannot read the message. Please try again")
//_log(ex.localizedMessage)
val spReq = Error()
spReq.sendErrorMsg(writer, "Cannot read the message. Please try again",client)
}
}
}
Update I added ServerThread code part too.
How to follow them and get their statuses?
CodePudding user response:
You can keep track of the threads and their state by having a Map for further reference
fun ClientHandler() {
try {
var count = 0
val serverSocket = ServerSocket(5000)
while (true) {
val socket: Socket = serverSocket.accept()
count
socket.reuseAddress = true
threads["thread name here"] = ServerThread(socket)
}
} catch (e: ConnectException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
} catch (e: Exception) {
e.printStackTrace()
}
}
fun stopServerThread(threadName: String) {
threads[threadName]?.interrupt()
}
internal inner class ServerThread(private val client: Socket) : Thread() {
private val reader = Scanner(client.getInputStream())
private val writer = PrintStream(client.getOutputStream())
private var receiveString: String = ""
init {
start()
}
override fun run() {
try {
while(reader.hasNextLine()){
if (isInterrupted) {
break
}
receiveString = reader.nextLine() ?: ""
if (receiveString != "") {
checkMessage(receiveString, writer, client)
}
}
} catch (ex: Exception) {
_log("Cannot read the message. Please try again")
//_log(ex.localizedMessage)
val spReq = Error()
spReq.sendErrorMsg(writer, "Cannot read the message. Please try again",client)
}
}
}