there’s a var aob = ByteArray(1025) for socket, ho...
# announcements
i
there’s a var aob = ByteArray(1025) for socket, how I can clean this aob?
g
what is
clean
? What do you want to achieve?
i
‘cause the client disconnect without a signal, and the last received message is still stored in aob, and when it received new messages, it will read the old messages, that’s not what I want, so I wonder if there’s method to clean or clear the bytearray aob
like memset() in C language
C language strings end with \0
so I wonder what bytearray in Kotlin would end with?
g
and when it received new messages, it will read the old messages
It’s not clear why it would work like that, it highly depends on your code, but I see problems with this behavior in general you already get this data from client and handle it somehow. If it was successful chunk of data you just pass it to processing, if it was error, you throw error, why would code read data from buffer again? Instead you should write it to buffer from socket, and read from buffer Anyway, the only way is to set values to 0 for this array is set every element to 0 or create a new one
Something like:
Copy code
fun ByteArray.setAll(value: Byte) {
    for (i in 0 until size) {
        this[i] = value
    }
}
k
ByteArrays don't end in anything in Kotlin/Java, they have a fixed easily obtained size instead unlike C.
g
they have a fixed easily obtained size instead unlike C
I’m not so familiar with C, but isn’t you also have fixed array size in C?
k
Yeah emphasis on the easily obtained part. I just explicitly mentioned it because it looks like he wants to use 0-terminators for strings or something like that.
g
Yeah, I see now
m
AFAIK in Kotlin new allocated arrays are always zero-filled.
c
That's correct. Maybe @Ifvwm is reusing the array somehow?
i
Copy code
var aob = ByteArray(1024)
while (true) {
  try{
  size = client.inputStream.read(aob)
  }catch(e:Exception){
     client.close()
     client = re_connect_network()
   }
  recvMsg = String(aob.sliceArray(0 until size), Charsets.UTF_8)
  if recvMsg.contains(“something”) doSomthing
  ...
}
that’s how I handle it, but when the connection is disconnected without an exit signal, so this try-catch will work and make a new connection, but the last received recvMsg will still go through those next if-else, so that’s I wonder if there’s a way can clear aob the ByteArray? also I find a way to solve this, just set size to 0, so sliceArray will not work, this can avoid those next if-else
c
It probably makes more sense to just throw away the old array and allocate a new one in the
catch
block:
aob = ByteArray(1024)
. It's likely that the overhead of the exception is far higher than the cost of re-allocating an array, and also zeroing an existing array in code might actually be slower.
g
Why not just move recvMsg to to
try
?
☝️ 1