Home > OS >  kotlin Socket connection regularly sends but does not receive data
kotlin Socket connection regularly sends but does not receive data

Time:10-24

I'm trying to write an application with a server in python. Everything is perfectly connected and the strings are sent from android, but it is not possible to get a string from the server. When trying to get a string, the stream is simply blocked, and if you set a timeout, then exception "timeout" is simply called, which is logical. I've tried everything, I'll show you at once all the code for both sending and receiving that I've come to at the moment (BufferedReader().ready() at the same time, everything works perfectly)

pythonServer

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(server_address)
server_socket.listen(1)

print ('Waiting for a client connection...')
connection, client_address = server_socket.accept()
print ('Connected to:', client_address)


# listen for data for forever
while True:
    data = connection.recv(data_size)
    print ('Received', data.decode('utf-8')) # print as raw bytes
    sizeOfMainMsg = int(data.decode('utf-8'))
    data = connection.recv(sizeOfMainMsg)
    print ('Received', data.decode('utf-8')) # print as raw bytes
    toSendTry = "Sendet "
    connection.send(bytes(toSendTry,'UTF-8'))

KotlinClient

clientSocket = Socket(SERVER_ADDRESS, SERVER_PORT)


clientSocketOut = clientSocket!!.getOutputStream()
clientSocketIn = clientSocket!!.getInputStream()

if (clientSocket != null) {
while (clientSocketOut != null && clientSocketIn != null && clientSocket!!.isConnected()) {
    var tmp = clientSocketIn!!.bufferedReader(Charsets.UTF_8)
    if(tmp.ready()){
        recived.add(tmp.readLine()) #This is where the problems occur
    }
    if (toSend.size > 0){
        for (nowMsg in toSend){
            clientSocketOut!!.write(nowMsg.toByteArray(Charsets.UTF_8).size.toString().toByteArray(Charsets.UTF_8))
            clientSocketOut!!.flush()
            clientSocketOut!!.write(nowMsg.toByteArray(Charsets.UTF_8))
            clientSocketOut!!.flush()
        }
        toSend.clear()
    }
}

(Needless to say, the kotlin client code is written in AsyncTask)

CodePudding user response:

Your client tries to read a line.

Now in order to succeed the server should have sent a line.

A line is NOT just a string.

Have a look at newline character.

  • Related