简体   繁体   中英

Java(Kotlin) Socket Server. Read continously

My server reading looks like this:

private fun init() {
        val inStream = BufferedInputStream(socket.getInputStream())
        val bytes = ByteArray(bufferSize)

        outStream = DataOutputStream(socket.getOutputStream())


        while (true) {
            val count = inStream.read(bytes, 0, bufferSize)

            if (count >= 0) {
                server.onReceive(this, bytes, count)
            }

        }
    }

First read waits until bytes received. But second doesn't wait. And loop is running forever and count is -1. I want to read bytes only when they received.

And loop is running forever

You're looping at end of stream. If count is -1 you should close the socket and exit the loop.

and count is -1

Exactly my point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM