Skip to content
Advertisement

Java send nullbyte (x00) as 1 character using AsynchronousSocketChannel

I need to send nullbyte as 1 character this code send its as 4 characters so not a nullbyte (x00) , it can’t be sending it as plain text. it’s sending to a flash client. I’m using AsynchronousSocketChannel to send the packets. the nullbyte is to tell the server that the packet has ended. for example when I send testx00 it sends it as testx00 which is wrong.

JavaScript

Advertisement

Answer

You should write a single null byte (0x00) after writing your string to the channel. What you’re doing is not it: you’re appending the string x00 instead (a backslash followed by an x and two 0s).

Against my first instincts, it seems it will work if you append the unicode character u0000 to your string, but the optimal way to do it is simply to put a byte with value 0 into the ByteBuffer after putting your string.

To be clear, I expected the null byte to be doubled when you append u0000, as Java encodes chars as UTF-16, hence on 2 bytes. But we’re explicitly encoding the String to UTF-8 to get it as bytes, so the null char is indeed encoded as a single null byte.

Here’s a small demo of this, showing for each method the length of data written to the channel, then its value as bytes:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement