Is there smth wrong with such code I posted in thi...
# getting-started
e
Is there smth wrong with such code I posted in this message thread? Specifically, is this OK to use multiple
.use
functions like that? Please take a look
Copy code
import java.net.ServerSocket
import java.io.PrintWriter

fun main() {
    val serverSocket =
        ServerSocket(6379).apply {
            reuseAddress = true
        }

    while (true) {
        serverSocket.accept().use { socket ->
            socket.getOutputStream().use { out ->
                PrintWriter(out, true).use { writer ->
                    writer.print("+PONG\r\n")
                }
            }
        }
    }
}
h
The usage of use is correct, but you should take a look at the while loop to not reopen and close the socket over and over.
e
uhh of course there's a new socket for each connected client. they're not re-opening the server socket
use
is fine but doesn't actually need to be used 3 times: • `PrintWriter`'s constructor doesn't throw and closing it closes the underlying
OutputStream
, so it could just be
Copy code
val out = socket.getOutputStream()
PrintWriter(out, true).use { writer ->
• you're not actually making use of any
PrintWriter
functionality, might as well use
Copy code
socket.getOutputStream().bufferedWriter().use { writer ->
Socket.close()
closes its own input and output streams, so you don't need to separately close them
Copy code
serverSocket.accept().use { socket ->
    val writer = socket.getOutputStream().bufferedWriter()
e
thanks