Socket - receive message only when client is terminated

46 Views Asked by At

I am new to network programming with kotlin, so I started with sockets. I got a client class and a server class. The client connects to the server, and sends a message. The problem now appers. The message will just be printed on the server-console if the client is closed. I don't know why :-( I think its a problem with the Bufferedreader, but I have no idea why and how to solve.

import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.ServerSocket

class MyServer(
    private val port: Int,
) {
    private val serverSocket: ServerSocket = createServerSocket()
    private val memberPool: MemberPool = MemberPool()

    private fun createServerSocket() : ServerSocket {
        try {
            return ServerSocket(port)
        }
        catch(e: Exception) {
            println(e.printStackTrace())
            throw(e)
        }
    }

    fun acceptClient() {
        try {
            val newClient = serverSocket.accept()
            println("Verbunden mit Client: ${newClient.inetAddress.hostAddress}")
            val newMember = Member(memberPool.nextFreeId, null, newClient)
            memberPool.addNewUser(newMember)

            Thread { handleClient(newMember) }.start()
        }
        catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun handleClient(member: Member) {
        try {
            println(member.clientSocket.isClosed) // false
            val m = BufferedReader(
                InputStreamReader(
                    member.clientSocket.getInputStream(),
                    Charsets.UTF_8
                )
            )

            m.forEachLine { line ->
                println("Message: $line")
            }
        }
        catch(e: Exception) {
            e.printStackTrace()
        }
    }

    fun closeServer() = serverSocket.close()
}
1

There are 1 best solutions below

0
SerhiiH On

This code looks OK, problem must be in the Client. Try this code for a client:

    val socket = Socket(serverAddress, portNumber)
    val writer = PrintWriter(socket.outputStream, true)
    val message = "Hello, server!"
    writer.println(message)

This should work, problem with your client might lay in it doesn't send new line separator after a message. Make sure you do it! On UNIX systems, line separator is "\n"; on Microsoft Windows systems - "\r\n".